3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-02-09T21:21:16Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
64 * Generate a unique ID for element
66 * @return {String} [id]
68 OO
.ui
.generateElementId = function () {
70 return 'oojsui-' + OO
.ui
.elementId
;
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
77 * @param {jQuery} element Element to test
80 OO
.ui
.isFocusableElement = function ( $element
) {
82 element
= $element
[ 0 ];
84 // Anything disabled is not focusable
85 if ( element
.disabled
) {
89 // Check if the element is visible
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr
.filters
.visible( element
) &&
93 // Check that all parents are visible
94 !$element
.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element
.contentEditable
=== 'true' ) {
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName
= element
.nodeName
.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
129 * Find a focusable child
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
135 OO
.ui
.findFocusable = function ( $container
, backwards
) {
136 var $focusable
= $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates
= $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
146 $focusableCandidates
.each( function () {
147 var $this = $( this );
148 if ( OO
.ui
.isFocusableElement( $this ) ) {
157 * Get the user's language and any fallback languages.
159 * These language codes are used to localize user interface elements in the user's language.
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
164 * @return {string[]} Language codes, in descending order of priority
166 OO
.ui
.getUserLanguages = function () {
171 * Get a value in an object keyed by language code.
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
178 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
181 // Requested language
185 // Known user language
186 langs
= OO
.ui
.getUserLanguages();
187 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
194 if ( obj
[ fallback
] ) {
195 return obj
[ fallback
];
197 // First existing language
198 for ( lang
in obj
) {
206 * Check if a node is contained within another node
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
216 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
218 if ( !Array
.isArray( containers
) ) {
219 containers
= [ containers
];
221 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
222 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
235 * Ported from: http://underscorejs.org/underscore.js
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
242 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
247 later = function () {
250 func
.apply( context
, args
);
253 if ( immediate
&& !timeout
) {
254 func
.apply( context
, args
);
256 clearTimeout( timeout
);
257 timeout
= setTimeout( later
, wait
);
262 * Proxy for `node.addEventListener( eventName, handler, true )`.
264 * @param {HTMLElement} node
265 * @param {string} eventName
266 * @param {Function} handler
269 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
270 node
.addEventListener( eventName
, handler
, true );
274 * Proxy for `node.removeEventListener( eventName, handler, true )`.
276 * @param {HTMLElement} node
277 * @param {string} eventName
278 * @param {Function} handler
281 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
282 node
.removeEventListener( eventName
, handler
, true );
286 * Reconstitute a JavaScript object corresponding to a widget created by
287 * the PHP implementation.
289 * This is an alias for `OO.ui.Element.static.infuse()`.
291 * @param {string|HTMLElement|jQuery} idOrNode
292 * A DOM id (if a string) or node for the widget to infuse.
293 * @return {OO.ui.Element}
294 * The `OO.ui.Element` corresponding to this (infusable) document node.
296 OO
.ui
.infuse = function ( idOrNode
) {
297 return OO
.ui
.Element
.static.infuse( idOrNode
);
302 * Message store for the default implementation of OO.ui.msg
304 * Environments that provide a localization system should not use this, but should override
305 * OO.ui.msg altogether.
310 // Tool tip for a button that moves items in a list down one place
311 'ooui-outline-control-move-down': 'Move item down',
312 // Tool tip for a button that moves items in a list up one place
313 'ooui-outline-control-move-up': 'Move item up',
314 // Tool tip for a button that removes items from a list
315 'ooui-outline-control-remove': 'Remove item',
316 // Label for the toolbar group that contains a list of all other available tools
317 'ooui-toolbar-more': 'More',
318 // Label for the fake tool that expands the full list of tools in a toolbar group
319 'ooui-toolgroup-expand': 'More',
320 // Label for the fake tool that collapses the full list of tools in a toolbar group
321 'ooui-toolgroup-collapse': 'Fewer',
322 // Default label for the accept button of a confirmation dialog
323 'ooui-dialog-message-accept': 'OK',
324 // Default label for the reject button of a confirmation dialog
325 'ooui-dialog-message-reject': 'Cancel',
326 // Title for process dialog error description
327 'ooui-dialog-process-error': 'Something went wrong',
328 // Label for process dialog dismiss error button, visible when describing errors
329 'ooui-dialog-process-dismiss': 'Dismiss',
330 // Label for process dialog retry action button, visible when describing only recoverable errors
331 'ooui-dialog-process-retry': 'Try again',
332 // Label for process dialog retry action button, visible when describing only warnings
333 'ooui-dialog-process-continue': 'Continue',
334 // Label for the file selection widget's select file button
335 'ooui-selectfile-button-select': 'Select a file',
336 // Label for the file selection widget if file selection is not supported
337 'ooui-selectfile-not-supported': 'File selection is not supported',
338 // Label for the file selection widget when no file is currently selected
339 'ooui-selectfile-placeholder': 'No file is selected',
340 // Label for the file selection widget's drop target
341 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
345 * Get a localized message.
347 * In environments that provide a localization system, this function should be overridden to
348 * return the message translated in the user's language. The default implementation always returns
351 * After the message key, message parameters may optionally be passed. In the default implementation,
352 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
353 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
354 * they support unnamed, ordered message parameters.
356 * @param {string} key Message key
357 * @param {Mixed...} [params] Message parameters
358 * @return {string} Translated message with parameters substituted
360 OO
.ui
.msg = function ( key
) {
361 var message
= messages
[ key
],
362 params
= Array
.prototype.slice
.call( arguments
, 1 );
363 if ( typeof message
=== 'string' ) {
364 // Perform $1 substitution
365 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
366 var i
= parseInt( n
, 10 );
367 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
370 // Return placeholder if message not found
371 message
= '[' + key
+ ']';
378 * Package a message and arguments for deferred resolution.
380 * Use this when you are statically specifying a message and the message may not yet be present.
382 * @param {string} key Message key
383 * @param {Mixed...} [params] Message parameters
384 * @return {Function} Function that returns the resolved message when executed
386 OO
.ui
.deferMsg = function () {
387 var args
= arguments
;
389 return OO
.ui
.msg
.apply( OO
.ui
, args
);
396 * If the message is a function it will be executed, otherwise it will pass through directly.
398 * @param {Function|string} msg Deferred message, or message text
399 * @return {string} Resolved message
401 OO
.ui
.resolveMsg = function ( msg
) {
402 if ( $.isFunction( msg
) ) {
409 * @param {string} url
412 OO
.ui
.isSafeUrl = function ( url
) {
413 // Keep this function in sync with php/Tag.php
414 var i
, protocolWhitelist
;
416 function stringStartsWith( haystack
, needle
) {
417 return haystack
.substr( 0, needle
.length
) === needle
;
420 protocolWhitelist
= [
421 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
422 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
423 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
430 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
431 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
436 // This matches '//' too
437 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
440 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
452 * Namespace for OOjs UI mixins.
454 * Mixins are named according to the type of object they are intended to
455 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
456 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
457 * is intended to be mixed in to an instance of OO.ui.Widget.
465 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
466 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
467 * connected to them and can't be interacted with.
473 * @param {Object} [config] Configuration options
474 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
475 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
477 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
478 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
479 * @cfg {string} [text] Text to insert
480 * @cfg {Array} [content] An array of content elements to append (after #text).
481 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
482 * Instances of OO.ui.Element will have their $element appended.
483 * @cfg {jQuery} [$content] Content elements to append (after #text).
484 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
485 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
486 * Data can also be specified with the #setData method.
488 OO
.ui
.Element
= function OoUiElement( config
) {
489 // Configuration initialization
490 config
= config
|| {};
495 this.data
= config
.data
;
496 this.$element
= config
.$element
||
497 $( document
.createElement( this.getTagName() ) );
498 this.elementGroup
= null;
499 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
502 if ( Array
.isArray( config
.classes
) ) {
503 this.$element
.addClass( config
.classes
.join( ' ' ) );
506 this.$element
.attr( 'id', config
.id
);
509 this.$element
.text( config
.text
);
511 if ( config
.content
) {
512 // The `content` property treats plain strings as text; use an
513 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
514 // appropriate $element appended.
515 this.$element
.append( config
.content
.map( function ( v
) {
516 if ( typeof v
=== 'string' ) {
517 // Escape string so it is properly represented in HTML.
518 return document
.createTextNode( v
);
519 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
522 } else if ( v
instanceof OO
.ui
.Element
) {
528 if ( config
.$content
) {
529 // The `$content` property treats plain strings as HTML.
530 this.$element
.append( config
.$content
);
536 OO
.initClass( OO
.ui
.Element
);
538 /* Static Properties */
541 * The name of the HTML tag used by the element.
543 * The static value may be ignored if the #getTagName method is overridden.
549 OO
.ui
.Element
.static.tagName
= 'div';
554 * Reconstitute a JavaScript object corresponding to a widget created
555 * by the PHP implementation.
557 * @param {string|HTMLElement|jQuery} idOrNode
558 * A DOM id (if a string) or node for the widget to infuse.
559 * @return {OO.ui.Element}
560 * The `OO.ui.Element` corresponding to this (infusable) document node.
561 * For `Tag` objects emitted on the HTML side (used occasionally for content)
562 * the value returned is a newly-created Element wrapping around the existing
565 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
566 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
567 // Verify that the type matches up.
568 // FIXME: uncomment after T89721 is fixed (see T90929)
570 if ( !( obj instanceof this['class'] ) ) {
571 throw new Error( 'Infusion type mismatch!' );
578 * Implementation helper for `infuse`; skips the type check and has an
579 * extra property so that only the top-level invocation touches the DOM.
581 * @param {string|HTMLElement|jQuery} idOrNode
582 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
583 * when the top-level widget of this infusion is inserted into DOM,
584 * replacing the original node; or false for top-level invocation.
585 * @return {OO.ui.Element}
587 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
588 // look for a cached result of a previous infusion.
589 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
590 if ( typeof idOrNode
=== 'string' ) {
592 $elem
= $( document
.getElementById( id
) );
594 $elem
= $( idOrNode
);
595 id
= $elem
.attr( 'id' );
597 if ( !$elem
.length
) {
598 throw new Error( 'Widget not found: ' + id
);
600 if ( $elem
[ 0 ].oouiInfused
) {
601 $elem
= $elem
[ 0 ].oouiInfused
;
603 data
= $elem
.data( 'ooui-infused' );
606 if ( data
=== true ) {
607 throw new Error( 'Circular dependency! ' + id
);
610 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
611 state
= data
.gatherPreInfuseState( $elem
);
612 // restore dynamic state after the new element is re-inserted into DOM under infused parent
613 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
614 infusedChildren
= $elem
.data( 'ooui-infused-children' );
615 if ( infusedChildren
&& infusedChildren
.length
) {
616 infusedChildren
.forEach( function ( data
) {
617 var state
= data
.gatherPreInfuseState( $elem
);
618 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
624 data
= $elem
.attr( 'data-ooui' );
626 throw new Error( 'No infusion data found: ' + id
);
629 data
= $.parseJSON( data
);
633 if ( !( data
&& data
._
) ) {
634 throw new Error( 'No valid infusion data found: ' + id
);
636 if ( data
._
=== 'Tag' ) {
637 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
638 return new OO
.ui
.Element( { $element
: $elem
} );
640 parts
= data
._
.split( '.' );
641 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
642 if ( cls
=== undefined ) {
643 // The PHP output might be old and not including the "OO.ui" prefix
644 // TODO: Remove this back-compat after next major release
645 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
646 if ( cls
=== undefined ) {
647 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
651 // Verify that we're creating an OO.ui.Element instance
654 while ( parent
!== undefined ) {
655 if ( parent
=== OO
.ui
.Element
) {
660 parent
= parent
.parent
;
663 if ( parent
!== OO
.ui
.Element
) {
664 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
667 if ( domPromise
=== false ) {
669 domPromise
= top
.promise();
671 $elem
.data( 'ooui-infused', true ); // prevent loops
672 data
.id
= id
; // implicit
673 infusedChildren
= [];
674 data
= OO
.copy( data
, null, function deserialize( value
) {
676 if ( OO
.isPlainObject( value
) ) {
678 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
679 infusedChildren
.push( infused
);
680 // Flatten the structure
681 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
682 infused
.$element
.removeData( 'ooui-infused-children' );
686 return new OO
.ui
.HtmlSnippet( value
.html
);
690 // allow widgets to reuse parts of the DOM
691 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
692 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
693 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
695 // jscs:disable requireCapitalizedConstructors
696 obj
= new cls( data
);
697 // jscs:enable requireCapitalizedConstructors
698 // now replace old DOM with this new DOM.
700 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
701 // so only mutate the DOM if we need to.
702 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
703 $elem
.replaceWith( obj
.$element
);
704 // This element is now gone from the DOM, but if anyone is holding a reference to it,
705 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
706 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
707 $elem
[ 0 ].oouiInfused
= obj
.$element
;
711 obj
.$element
.data( 'ooui-infused', obj
);
712 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
713 // set the 'data-ooui' attribute so we can identify infused widgets
714 obj
.$element
.attr( 'data-ooui', '' );
715 // restore dynamic state after the new element is inserted into DOM
716 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
721 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
723 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
724 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
725 * constructor, which will be given the enhanced config.
728 * @param {HTMLElement} node
729 * @param {Object} config
732 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
737 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
738 * (and its children) that represent an Element of the same class and the given configuration,
739 * generated by the PHP implementation.
741 * This method is called just before `node` is detached from the DOM. The return value of this
742 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
743 * is inserted into DOM to replace `node`.
746 * @param {HTMLElement} node
747 * @param {Object} config
750 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
755 * Get a jQuery function within a specific document.
758 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
759 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
761 * @return {Function} Bound jQuery function
763 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
764 function wrapper( selector
) {
765 return $( selector
, wrapper
.context
);
768 wrapper
.context
= this.getDocument( context
);
771 wrapper
.$iframe
= $iframe
;
778 * Get the document of an element.
781 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
782 * @return {HTMLDocument|null} Document object
784 OO
.ui
.Element
.static.getDocument = function ( obj
) {
785 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
786 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
787 // Empty jQuery selections might have a context
794 ( obj
.nodeType
=== 9 && obj
) ||
799 * Get the window of an element or document.
802 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
803 * @return {Window} Window object
805 OO
.ui
.Element
.static.getWindow = function ( obj
) {
806 var doc
= this.getDocument( obj
);
807 return doc
.defaultView
;
811 * Get the direction of an element or document.
814 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
815 * @return {string} Text direction, either 'ltr' or 'rtl'
817 OO
.ui
.Element
.static.getDir = function ( obj
) {
820 if ( obj
instanceof jQuery
) {
823 isDoc
= obj
.nodeType
=== 9;
824 isWin
= obj
.document
!== undefined;
825 if ( isDoc
|| isWin
) {
831 return $( obj
).css( 'direction' );
835 * Get the offset between two frames.
837 * TODO: Make this function not use recursion.
840 * @param {Window} from Window of the child frame
841 * @param {Window} [to=window] Window of the parent frame
842 * @param {Object} [offset] Offset to start with, used internally
843 * @return {Object} Offset object, containing left and top properties
845 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
846 var i
, len
, frames
, frame
, rect
;
852 offset
= { top
: 0, left
: 0 };
854 if ( from.parent
=== from ) {
858 // Get iframe element
859 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
860 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
861 if ( frames
[ i
].contentWindow
=== from ) {
867 // Recursively accumulate offset values
869 rect
= frame
.getBoundingClientRect();
870 offset
.left
+= rect
.left
;
871 offset
.top
+= rect
.top
;
873 this.getFrameOffset( from.parent
, offset
);
880 * Get the offset between two elements.
882 * The two elements may be in a different frame, but in that case the frame $element is in must
883 * be contained in the frame $anchor is in.
886 * @param {jQuery} $element Element whose position to get
887 * @param {jQuery} $anchor Element to get $element's position relative to
888 * @return {Object} Translated position coordinates, containing top and left properties
890 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
891 var iframe
, iframePos
,
892 pos
= $element
.offset(),
893 anchorPos
= $anchor
.offset(),
894 elementDocument
= this.getDocument( $element
),
895 anchorDocument
= this.getDocument( $anchor
);
897 // If $element isn't in the same document as $anchor, traverse up
898 while ( elementDocument
!== anchorDocument
) {
899 iframe
= elementDocument
.defaultView
.frameElement
;
901 throw new Error( '$element frame is not contained in $anchor frame' );
903 iframePos
= $( iframe
).offset();
904 pos
.left
+= iframePos
.left
;
905 pos
.top
+= iframePos
.top
;
906 elementDocument
= iframe
.ownerDocument
;
908 pos
.left
-= anchorPos
.left
;
909 pos
.top
-= anchorPos
.top
;
914 * Get element border sizes.
917 * @param {HTMLElement} el Element to measure
918 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
920 OO
.ui
.Element
.static.getBorders = function ( el
) {
921 var doc
= el
.ownerDocument
,
922 win
= doc
.defaultView
,
923 style
= win
.getComputedStyle( el
, null ),
925 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
926 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
927 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
928 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
939 * Get dimensions of an element or window.
942 * @param {HTMLElement|Window} el Element to measure
943 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
945 OO
.ui
.Element
.static.getDimensions = function ( el
) {
947 doc
= el
.ownerDocument
|| el
.document
,
948 win
= doc
.defaultView
;
950 if ( win
=== el
|| el
=== doc
.documentElement
) {
953 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
955 top
: $win
.scrollTop(),
956 left
: $win
.scrollLeft()
958 scrollbar
: { right
: 0, bottom
: 0 },
962 bottom
: $win
.innerHeight(),
963 right
: $win
.innerWidth()
969 borders
: this.getBorders( el
),
971 top
: $el
.scrollTop(),
972 left
: $el
.scrollLeft()
975 right
: $el
.innerWidth() - el
.clientWidth
,
976 bottom
: $el
.innerHeight() - el
.clientHeight
978 rect
: el
.getBoundingClientRect()
984 * Get scrollable object parent
986 * documentElement can't be used to get or set the scrollTop
987 * property on Blink. Changing and testing its value lets us
988 * use 'body' or 'documentElement' based on what is working.
990 * https://code.google.com/p/chromium/issues/detail?id=303131
993 * @param {HTMLElement} el Element to find scrollable parent for
994 * @return {HTMLElement} Scrollable parent
996 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
999 if ( OO
.ui
.scrollableElement
=== undefined ) {
1000 body
= el
.ownerDocument
.body
;
1001 scrollTop
= body
.scrollTop
;
1004 if ( body
.scrollTop
=== 1 ) {
1005 body
.scrollTop
= scrollTop
;
1006 OO
.ui
.scrollableElement
= 'body';
1008 OO
.ui
.scrollableElement
= 'documentElement';
1012 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1016 * Get closest scrollable container.
1018 * Traverses up until either a scrollable element or the root is reached, in which case the window
1022 * @param {HTMLElement} el Element to find scrollable container for
1023 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1024 * @return {HTMLElement} Closest scrollable container
1026 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1028 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1029 props
= [ 'overflow-x', 'overflow-y' ],
1030 $parent
= $( el
).parent();
1032 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1033 props
= [ 'overflow-' + dimension
];
1036 while ( $parent
.length
) {
1037 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1038 return $parent
[ 0 ];
1042 val
= $parent
.css( props
[ i
] );
1043 if ( val
=== 'auto' || val
=== 'scroll' ) {
1044 return $parent
[ 0 ];
1047 $parent
= $parent
.parent();
1049 return this.getDocument( el
).body
;
1053 * Scroll element into view.
1056 * @param {HTMLElement} el Element to scroll into view
1057 * @param {Object} [config] Configuration options
1058 * @param {string} [config.duration] jQuery animation duration value
1059 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1060 * to scroll in both directions
1061 * @param {Function} [config.complete] Function to call when scrolling completes
1063 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1064 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1066 // Configuration initialization
1067 config
= config
|| {};
1070 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1071 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1073 eld
= this.getDimensions( el
);
1074 scd
= this.getDimensions( sc
);
1075 $win
= $( this.getWindow( el
) );
1077 // Compute the distances between the edges of el and the edges of the scroll viewport
1078 if ( $sc
.is( 'html, body' ) ) {
1079 // If the scrollable container is the root, this is easy
1082 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1083 left
: eld
.rect
.left
,
1084 right
: $win
.innerWidth() - eld
.rect
.right
1087 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1089 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1090 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1091 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1092 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1096 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1097 if ( rel
.top
< 0 ) {
1098 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1099 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1100 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1103 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1104 if ( rel
.left
< 0 ) {
1105 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1106 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1107 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1110 if ( !$.isEmptyObject( anim
) ) {
1111 $sc
.stop( true ).animate( anim
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1113 $sc
.queue( function ( next
) {
1126 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1127 * and reserve space for them, because it probably doesn't.
1129 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1130 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1131 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1132 * and then reattach (or show) them back.
1135 * @param {HTMLElement} el Element to reconsider the scrollbars on
1137 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1138 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1139 // Save scroll position
1140 scrollLeft
= el
.scrollLeft
;
1141 scrollTop
= el
.scrollTop
;
1142 // Detach all children
1143 while ( el
.firstChild
) {
1144 nodes
.push( el
.firstChild
);
1145 el
.removeChild( el
.firstChild
);
1148 void el
.offsetHeight
;
1149 // Reattach all children
1150 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1151 el
.appendChild( nodes
[ i
] );
1153 // Restore scroll position (no-op if scrollbars disappeared)
1154 el
.scrollLeft
= scrollLeft
;
1155 el
.scrollTop
= scrollTop
;
1161 * Toggle visibility of an element.
1163 * @param {boolean} [show] Make element visible, omit to toggle visibility
1167 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1168 show
= show
=== undefined ? !this.visible
: !!show
;
1170 if ( show
!== this.isVisible() ) {
1171 this.visible
= show
;
1172 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1173 this.emit( 'toggle', show
);
1180 * Check if element is visible.
1182 * @return {boolean} element is visible
1184 OO
.ui
.Element
.prototype.isVisible = function () {
1185 return this.visible
;
1191 * @return {Mixed} Element data
1193 OO
.ui
.Element
.prototype.getData = function () {
1200 * @param {Mixed} Element data
1203 OO
.ui
.Element
.prototype.setData = function ( data
) {
1209 * Check if element supports one or more methods.
1211 * @param {string|string[]} methods Method or list of methods to check
1212 * @return {boolean} All methods are supported
1214 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1218 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1219 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1220 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1225 return methods
.length
=== support
;
1229 * Update the theme-provided classes.
1231 * @localdoc This is called in element mixins and widget classes any time state changes.
1232 * Updating is debounced, minimizing overhead of changing multiple attributes and
1233 * guaranteeing that theme updates do not occur within an element's constructor
1235 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1236 this.debouncedUpdateThemeClassesHandler();
1241 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1242 * make them synchronous.
1244 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1245 OO
.ui
.theme
.updateElementClasses( this );
1249 * Get the HTML tag name.
1251 * Override this method to base the result on instance information.
1253 * @return {string} HTML tag name
1255 OO
.ui
.Element
.prototype.getTagName = function () {
1256 return this.constructor.static.tagName
;
1260 * Check if the element is attached to the DOM
1261 * @return {boolean} The element is attached to the DOM
1263 OO
.ui
.Element
.prototype.isElementAttached = function () {
1264 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1268 * Get the DOM document.
1270 * @return {HTMLDocument} Document object
1272 OO
.ui
.Element
.prototype.getElementDocument = function () {
1273 // Don't cache this in other ways either because subclasses could can change this.$element
1274 return OO
.ui
.Element
.static.getDocument( this.$element
);
1278 * Get the DOM window.
1280 * @return {Window} Window object
1282 OO
.ui
.Element
.prototype.getElementWindow = function () {
1283 return OO
.ui
.Element
.static.getWindow( this.$element
);
1287 * Get closest scrollable container.
1289 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1290 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1294 * Get group element is in.
1296 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1298 OO
.ui
.Element
.prototype.getElementGroup = function () {
1299 return this.elementGroup
;
1303 * Set group element is in.
1305 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1308 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1309 this.elementGroup
= group
;
1314 * Scroll element into view.
1316 * @param {Object} [config] Configuration options
1318 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1319 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1323 * Restore the pre-infusion dynamic state for this widget.
1325 * This method is called after #$element has been inserted into DOM. The parameter is the return
1326 * value of #gatherPreInfuseState.
1329 * @param {Object} state
1331 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1335 * Wraps an HTML snippet for use with configuration values which default
1336 * to strings. This bypasses the default html-escaping done to string
1342 * @param {string} [content] HTML content
1344 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1346 this.content
= content
;
1351 OO
.initClass( OO
.ui
.HtmlSnippet
);
1358 * @return {string} Unchanged HTML snippet.
1360 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1361 return this.content
;
1365 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1366 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1367 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1368 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1369 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1373 * @extends OO.ui.Element
1374 * @mixins OO.EventEmitter
1377 * @param {Object} [config] Configuration options
1379 OO
.ui
.Layout
= function OoUiLayout( config
) {
1380 // Configuration initialization
1381 config
= config
|| {};
1383 // Parent constructor
1384 OO
.ui
.Layout
.parent
.call( this, config
);
1386 // Mixin constructors
1387 OO
.EventEmitter
.call( this );
1390 this.$element
.addClass( 'oo-ui-layout' );
1395 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1396 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1399 * Widgets are compositions of one or more OOjs UI elements that users can both view
1400 * and interact with. All widgets can be configured and modified via a standard API,
1401 * and their state can change dynamically according to a model.
1405 * @extends OO.ui.Element
1406 * @mixins OO.EventEmitter
1409 * @param {Object} [config] Configuration options
1410 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1411 * appearance reflects this state.
1413 OO
.ui
.Widget
= function OoUiWidget( config
) {
1414 // Initialize config
1415 config
= $.extend( { disabled
: false }, config
);
1417 // Parent constructor
1418 OO
.ui
.Widget
.parent
.call( this, config
);
1420 // Mixin constructors
1421 OO
.EventEmitter
.call( this );
1424 this.disabled
= null;
1425 this.wasDisabled
= null;
1428 this.$element
.addClass( 'oo-ui-widget' );
1429 this.setDisabled( !!config
.disabled
);
1434 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1435 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1437 /* Static Properties */
1440 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1441 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1446 * @property {boolean}
1448 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1455 * A 'disable' event is emitted when the disabled state of the widget changes
1456 * (i.e. on disable **and** enable).
1458 * @param {boolean} disabled Widget is disabled
1464 * A 'toggle' event is emitted when the visibility of the widget changes.
1466 * @param {boolean} visible Widget is visible
1472 * Check if the widget is disabled.
1474 * @return {boolean} Widget is disabled
1476 OO
.ui
.Widget
.prototype.isDisabled = function () {
1477 return this.disabled
;
1481 * Set the 'disabled' state of the widget.
1483 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1485 * @param {boolean} disabled Disable widget
1488 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1491 this.disabled
= !!disabled
;
1492 isDisabled
= this.isDisabled();
1493 if ( isDisabled
!== this.wasDisabled
) {
1494 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1495 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1496 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1497 this.emit( 'disable', isDisabled
);
1498 this.updateThemeClasses();
1500 this.wasDisabled
= isDisabled
;
1506 * Update the disabled state, in case of changes in parent widget.
1510 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1511 this.setDisabled( this.disabled
);
1522 * @param {Object} [config] Configuration options
1524 OO
.ui
.Theme
= function OoUiTheme( config
) {
1525 // Configuration initialization
1526 config
= config
|| {};
1531 OO
.initClass( OO
.ui
.Theme
);
1536 * Get a list of classes to be applied to a widget.
1538 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1539 * otherwise state transitions will not work properly.
1541 * @param {OO.ui.Element} element Element for which to get classes
1542 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1544 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1545 return { on
: [], off
: [] };
1549 * Update CSS classes provided by the theme.
1551 * For elements with theme logic hooks, this should be called any time there's a state change.
1553 * @param {OO.ui.Element} element Element for which to update classes
1554 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1556 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1557 var $elements
= $( [] ),
1558 classes
= this.getElementClasses( element
);
1560 if ( element
.$icon
) {
1561 $elements
= $elements
.add( element
.$icon
);
1563 if ( element
.$indicator
) {
1564 $elements
= $elements
.add( element
.$indicator
);
1568 .removeClass( classes
.off
.join( ' ' ) )
1569 .addClass( classes
.on
.join( ' ' ) );
1573 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1574 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1575 * order in which users will navigate through the focusable elements via the "tab" key.
1578 * // TabIndexedElement is mixed into the ButtonWidget class
1579 * // to provide a tabIndex property.
1580 * var button1 = new OO.ui.ButtonWidget( {
1584 * var button2 = new OO.ui.ButtonWidget( {
1588 * var button3 = new OO.ui.ButtonWidget( {
1592 * var button4 = new OO.ui.ButtonWidget( {
1596 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1602 * @param {Object} [config] Configuration options
1603 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1604 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1605 * functionality will be applied to it instead.
1606 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1607 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1608 * to remove the element from the tab-navigation flow.
1610 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1611 // Configuration initialization
1612 config
= $.extend( { tabIndex
: 0 }, config
);
1615 this.$tabIndexed
= null;
1616 this.tabIndex
= null;
1619 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1622 this.setTabIndex( config
.tabIndex
);
1623 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1628 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1633 * Set the element that should use the tabindex functionality.
1635 * This method is used to retarget a tabindex mixin so that its functionality applies
1636 * to the specified element. If an element is currently using the functionality, the mixin’s
1637 * effect on that element is removed before the new element is set up.
1639 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1642 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1643 var tabIndex
= this.tabIndex
;
1644 // Remove attributes from old $tabIndexed
1645 this.setTabIndex( null );
1646 // Force update of new $tabIndexed
1647 this.$tabIndexed
= $tabIndexed
;
1648 this.tabIndex
= tabIndex
;
1649 return this.updateTabIndex();
1653 * Set the value of the tabindex.
1655 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1658 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1659 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1661 if ( this.tabIndex
!== tabIndex
) {
1662 this.tabIndex
= tabIndex
;
1663 this.updateTabIndex();
1670 * Update the `tabindex` attribute, in case of changes to tab index or
1676 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1677 if ( this.$tabIndexed
) {
1678 if ( this.tabIndex
!== null ) {
1679 // Do not index over disabled elements
1680 this.$tabIndexed
.attr( {
1681 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1682 // Support: ChromeVox and NVDA
1683 // These do not seem to inherit aria-disabled from parent elements
1684 'aria-disabled': this.isDisabled().toString()
1687 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1694 * Handle disable events.
1697 * @param {boolean} disabled Element is disabled
1699 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1700 this.updateTabIndex();
1704 * Get the value of the tabindex.
1706 * @return {number|null} Tabindex value
1708 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1709 return this.tabIndex
;
1713 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1714 * interface element that can be configured with access keys for accessibility.
1715 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1717 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1722 * @param {Object} [config] Configuration options
1723 * @cfg {jQuery} [$button] The button element created by the class.
1724 * If this configuration is omitted, the button element will use a generated `<a>`.
1725 * @cfg {boolean} [framed=true] Render the button with a frame
1727 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1728 // Configuration initialization
1729 config
= config
|| {};
1732 this.$button
= null;
1734 this.active
= false;
1735 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1736 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1737 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1738 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1739 this.onClickHandler
= this.onClick
.bind( this );
1740 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1743 this.$element
.addClass( 'oo-ui-buttonElement' );
1744 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1745 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1750 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1752 /* Static Properties */
1755 * Cancel mouse down events.
1757 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1758 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1759 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1764 * @property {boolean}
1766 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1771 * A 'click' event is emitted when the button element is clicked.
1779 * Set the button element.
1781 * This method is used to retarget a button mixin so that its functionality applies to
1782 * the specified button element instead of the one created by the class. If a button element
1783 * is already set, the method will remove the mixin’s effect on that element.
1785 * @param {jQuery} $button Element to use as button
1787 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1788 if ( this.$button
) {
1790 .removeClass( 'oo-ui-buttonElement-button' )
1791 .removeAttr( 'role accesskey' )
1793 mousedown
: this.onMouseDownHandler
,
1794 keydown
: this.onKeyDownHandler
,
1795 click
: this.onClickHandler
,
1796 keypress
: this.onKeyPressHandler
1800 this.$button
= $button
1801 .addClass( 'oo-ui-buttonElement-button' )
1802 .attr( { role
: 'button' } )
1804 mousedown
: this.onMouseDownHandler
,
1805 keydown
: this.onKeyDownHandler
,
1806 click
: this.onClickHandler
,
1807 keypress
: this.onKeyPressHandler
1812 * Handles mouse down events.
1815 * @param {jQuery.Event} e Mouse down event
1817 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1818 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1821 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1822 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1823 // reliably remove the pressed class
1824 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1825 // Prevent change of focus unless specifically configured otherwise
1826 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1832 * Handles mouse up events.
1835 * @param {MouseEvent} e Mouse up event
1837 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1838 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1841 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1842 // Stop listening for mouseup, since we only needed this once
1843 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1847 * Handles mouse click events.
1850 * @param {jQuery.Event} e Mouse click event
1853 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
1854 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
1855 if ( this.emit( 'click' ) ) {
1862 * Handles key down events.
1865 * @param {jQuery.Event} e Key down event
1867 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
1868 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1871 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1872 // Run the keyup handler no matter where the key is when the button is let go, so we can
1873 // reliably remove the pressed class
1874 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
1878 * Handles key up events.
1881 * @param {KeyboardEvent} e Key up event
1883 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
1884 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1887 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1888 // Stop listening for keyup, since we only needed this once
1889 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
1893 * Handles key press events.
1896 * @param {jQuery.Event} e Key press event
1899 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
1900 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1901 if ( this.emit( 'click' ) ) {
1908 * Check if button has a frame.
1910 * @return {boolean} Button is framed
1912 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
1917 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
1919 * @param {boolean} [framed] Make button framed, omit to toggle
1922 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
1923 framed
= framed
=== undefined ? !this.framed
: !!framed
;
1924 if ( framed
!== this.framed
) {
1925 this.framed
= framed
;
1927 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
1928 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
1929 this.updateThemeClasses();
1936 * Set the button's active state.
1938 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
1939 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
1940 * for other button types.
1942 * @param {boolean} value Make button active
1945 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
1946 this.active
= !!value
;
1947 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
1952 * Check if the button is active
1954 * @return {boolean} The button is active
1956 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
1961 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
1962 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
1963 * items from the group is done through the interface the class provides.
1964 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1966 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
1972 * @param {Object} [config] Configuration options
1973 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
1974 * is omitted, the group element will use a generated `<div>`.
1976 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
1977 // Configuration initialization
1978 config
= config
|| {};
1983 this.aggregateItemEvents
= {};
1986 this.setGroupElement( config
.$group
|| $( '<div>' ) );
1992 * Set the group element.
1994 * If an element is already set, items will be moved to the new element.
1996 * @param {jQuery} $group Element to use as group
1998 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2001 this.$group
= $group
;
2002 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2003 this.$group
.append( this.items
[ i
].$element
);
2008 * Check if a group contains no items.
2010 * @return {boolean} Group is empty
2012 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2013 return !this.items
.length
;
2017 * Get all items in the group.
2019 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2020 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2023 * @return {OO.ui.Element[]} An array of items.
2025 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2026 return this.items
.slice( 0 );
2030 * Get an item by its data.
2032 * Only the first item with matching data will be returned. To return all matching items,
2033 * use the #getItemsFromData method.
2035 * @param {Object} data Item data to search for
2036 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2038 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2040 hash
= OO
.getHash( data
);
2042 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2043 item
= this.items
[ i
];
2044 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2053 * Get items by their data.
2055 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2057 * @param {Object} data Item data to search for
2058 * @return {OO.ui.Element[]} Items with equivalent data
2060 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2062 hash
= OO
.getHash( data
),
2065 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2066 item
= this.items
[ i
];
2067 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2076 * Aggregate the events emitted by the group.
2078 * When events are aggregated, the group will listen to all contained items for the event,
2079 * and then emit the event under a new name. The new event will contain an additional leading
2080 * parameter containing the item that emitted the original event. Other arguments emitted from
2081 * the original event are passed through.
2083 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2084 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2085 * A `null` value will remove aggregated events.
2087 * @throws {Error} An error is thrown if aggregation already exists.
2089 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2090 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2092 for ( itemEvent
in events
) {
2093 groupEvent
= events
[ itemEvent
];
2095 // Remove existing aggregated event
2096 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2097 // Don't allow duplicate aggregations
2099 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2101 // Remove event aggregation from existing items
2102 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2103 item
= this.items
[ i
];
2104 if ( item
.connect
&& item
.disconnect
) {
2106 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2107 item
.disconnect( this, remove
);
2110 // Prevent future items from aggregating event
2111 delete this.aggregateItemEvents
[ itemEvent
];
2114 // Add new aggregate event
2116 // Make future items aggregate event
2117 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2118 // Add event aggregation to existing items
2119 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2120 item
= this.items
[ i
];
2121 if ( item
.connect
&& item
.disconnect
) {
2123 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2124 item
.connect( this, add
);
2132 * Add items to the group.
2134 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2135 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2137 * @param {OO.ui.Element[]} items An array of items to add to the group
2138 * @param {number} [index] Index of the insertion point
2141 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2142 var i
, len
, item
, event
, events
, currentIndex
,
2145 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2148 // Check if item exists then remove it first, effectively "moving" it
2149 currentIndex
= this.items
.indexOf( item
);
2150 if ( currentIndex
>= 0 ) {
2151 this.removeItems( [ item
] );
2152 // Adjust index to compensate for removal
2153 if ( currentIndex
< index
) {
2158 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2160 for ( event
in this.aggregateItemEvents
) {
2161 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
2163 item
.connect( this, events
);
2165 item
.setElementGroup( this );
2166 itemElements
.push( item
.$element
.get( 0 ) );
2169 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2170 this.$group
.append( itemElements
);
2171 this.items
.push
.apply( this.items
, items
);
2172 } else if ( index
=== 0 ) {
2173 this.$group
.prepend( itemElements
);
2174 this.items
.unshift
.apply( this.items
, items
);
2176 this.items
[ index
].$element
.before( itemElements
);
2177 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2184 * Remove the specified items from a group.
2186 * Removed items are detached (not removed) from the DOM so that they may be reused.
2187 * To remove all items from a group, you may wish to use the #clearItems method instead.
2189 * @param {OO.ui.Element[]} items An array of items to remove
2192 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2193 var i
, len
, item
, index
, remove
, itemEvent
;
2195 // Remove specific items
2196 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2198 index
= this.items
.indexOf( item
);
2199 if ( index
!== -1 ) {
2201 item
.connect
&& item
.disconnect
&&
2202 !$.isEmptyObject( this.aggregateItemEvents
)
2205 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2206 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2208 item
.disconnect( this, remove
);
2210 item
.setElementGroup( null );
2211 this.items
.splice( index
, 1 );
2212 item
.$element
.detach();
2220 * Clear all items from the group.
2222 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2223 * To remove only a subset of items from a group, use the #removeItems method.
2227 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2228 var i
, len
, item
, remove
, itemEvent
;
2231 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2232 item
= this.items
[ i
];
2234 item
.connect
&& item
.disconnect
&&
2235 !$.isEmptyObject( this.aggregateItemEvents
)
2238 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2239 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2241 item
.disconnect( this, remove
);
2243 item
.setElementGroup( null );
2244 item
.$element
.detach();
2252 * IconElement is often mixed into other classes to generate an icon.
2253 * Icons are graphics, about the size of normal text. They are used to aid the user
2254 * in locating a control or to convey information in a space-efficient way. See the
2255 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2256 * included in the library.
2258 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2264 * @param {Object} [config] Configuration options
2265 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2266 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2267 * the icon element be set to an existing icon instead of the one generated by this class, set a
2268 * value using a jQuery selection. For example:
2270 * // Use a <div> tag instead of a <span>
2272 * // Use an existing icon element instead of the one generated by the class
2273 * $icon: this.$element
2274 * // Use an icon element from a child widget
2275 * $icon: this.childwidget.$element
2276 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2277 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2278 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2279 * by the user's language.
2281 * Example of an i18n map:
2283 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2284 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2285 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2286 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2287 * text. The icon title is displayed when users move the mouse over the icon.
2289 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2290 // Configuration initialization
2291 config
= config
|| {};
2296 this.iconTitle
= null;
2299 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2300 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2301 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2306 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2308 /* Static Properties */
2311 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2312 * for i18n purposes and contains a `default` icon name and additional names keyed by
2313 * language code. The `default` name is used when no icon is keyed by the user's language.
2315 * Example of an i18n map:
2317 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2319 * Note: the static property will be overridden if the #icon configuration is used.
2323 * @property {Object|string}
2325 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2328 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2329 * function that returns title text, or `null` for no title.
2331 * The static property will be overridden if the #iconTitle configuration is used.
2335 * @property {string|Function|null}
2337 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2342 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2343 * applies to the specified icon element instead of the one created by the class. If an icon
2344 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2345 * and mixin methods will no longer affect the element.
2347 * @param {jQuery} $icon Element to use as icon
2349 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2352 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2353 .removeAttr( 'title' );
2357 .addClass( 'oo-ui-iconElement-icon' )
2358 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2359 if ( this.iconTitle
!== null ) {
2360 this.$icon
.attr( 'title', this.iconTitle
);
2363 this.updateThemeClasses();
2367 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2368 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2371 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2372 * by language code, or `null` to remove the icon.
2375 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2376 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2377 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2379 if ( this.icon
!== icon
) {
2381 if ( this.icon
!== null ) {
2382 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2384 if ( icon
!== null ) {
2385 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2391 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2392 this.updateThemeClasses();
2398 * Set the icon title. Use `null` to remove the title.
2400 * @param {string|Function|null} iconTitle A text string used as the icon title,
2401 * a function that returns title text, or `null` for no title.
2404 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2405 iconTitle
= typeof iconTitle
=== 'function' ||
2406 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2407 OO
.ui
.resolveMsg( iconTitle
) : null;
2409 if ( this.iconTitle
!== iconTitle
) {
2410 this.iconTitle
= iconTitle
;
2412 if ( this.iconTitle
!== null ) {
2413 this.$icon
.attr( 'title', iconTitle
);
2415 this.$icon
.removeAttr( 'title' );
2424 * Get the symbolic name of the icon.
2426 * @return {string} Icon name
2428 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2433 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2435 * @return {string} Icon title text
2437 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2438 return this.iconTitle
;
2442 * IndicatorElement is often mixed into other classes to generate an indicator.
2443 * Indicators are small graphics that are generally used in two ways:
2445 * - To draw attention to the status of an item. For example, an indicator might be
2446 * used to show that an item in a list has errors that need to be resolved.
2447 * - To clarify the function of a control that acts in an exceptional way (a button
2448 * that opens a menu instead of performing an action directly, for example).
2450 * For a list of indicators included in the library, please see the
2451 * [OOjs UI documentation on MediaWiki] [1].
2453 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2459 * @param {Object} [config] Configuration options
2460 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2461 * configuration is omitted, the indicator element will use a generated `<span>`.
2462 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2463 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2465 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2466 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2467 * or a function that returns title text. The indicator title is displayed when users move
2468 * the mouse over the indicator.
2470 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2471 // Configuration initialization
2472 config
= config
|| {};
2475 this.$indicator
= null;
2476 this.indicator
= null;
2477 this.indicatorTitle
= null;
2480 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2481 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2482 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2487 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2489 /* Static Properties */
2492 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2493 * The static property will be overridden if the #indicator configuration is used.
2497 * @property {string|null}
2499 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2502 * A text string used as the indicator title, a function that returns title text, or `null`
2503 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2507 * @property {string|Function|null}
2509 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2514 * Set the indicator element.
2516 * If an element is already set, it will be cleaned up before setting up the new element.
2518 * @param {jQuery} $indicator Element to use as indicator
2520 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2521 if ( this.$indicator
) {
2523 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2524 .removeAttr( 'title' );
2527 this.$indicator
= $indicator
2528 .addClass( 'oo-ui-indicatorElement-indicator' )
2529 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2530 if ( this.indicatorTitle
!== null ) {
2531 this.$indicator
.attr( 'title', this.indicatorTitle
);
2534 this.updateThemeClasses();
2538 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2540 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2543 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2544 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2546 if ( this.indicator
!== indicator
) {
2547 if ( this.$indicator
) {
2548 if ( this.indicator
!== null ) {
2549 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2551 if ( indicator
!== null ) {
2552 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2555 this.indicator
= indicator
;
2558 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2559 this.updateThemeClasses();
2565 * Set the indicator title.
2567 * The title is displayed when a user moves the mouse over the indicator.
2569 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
2570 * `null` for no indicator title
2573 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2574 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2575 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2576 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2578 if ( this.indicatorTitle
!== indicatorTitle
) {
2579 this.indicatorTitle
= indicatorTitle
;
2580 if ( this.$indicator
) {
2581 if ( this.indicatorTitle
!== null ) {
2582 this.$indicator
.attr( 'title', indicatorTitle
);
2584 this.$indicator
.removeAttr( 'title' );
2593 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2595 * @return {string} Symbolic name of indicator
2597 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2598 return this.indicator
;
2602 * Get the indicator title.
2604 * The title is displayed when a user moves the mouse over the indicator.
2606 * @return {string} Indicator title text
2608 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2609 return this.indicatorTitle
;
2613 * LabelElement is often mixed into other classes to generate a label, which
2614 * helps identify the function of an interface element.
2615 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2623 * @param {Object} [config] Configuration options
2624 * @cfg {jQuery} [$label] The label element created by the class. If this
2625 * configuration is omitted, the label element will use a generated `<span>`.
2626 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2627 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2628 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2629 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2630 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
2631 * The label will be truncated to fit if necessary.
2633 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2634 // Configuration initialization
2635 config
= config
|| {};
2640 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
2643 this.setLabel( config
.label
|| this.constructor.static.label
);
2644 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2649 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2654 * @event labelChange
2655 * @param {string} value
2658 /* Static Properties */
2661 * The label text. The label can be specified as a plaintext string, a function that will
2662 * produce a string in the future, or `null` for no label. The static value will
2663 * be overridden if a label is specified with the #label config option.
2667 * @property {string|Function|null}
2669 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2674 * Set the label element.
2676 * If an element is already set, it will be cleaned up before setting up the new element.
2678 * @param {jQuery} $label Element to use as label
2680 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2681 if ( this.$label
) {
2682 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2685 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2686 this.setLabelContent( this.label
);
2692 * An empty string will result in the label being hidden. A string containing only whitespace will
2693 * be converted to a single ` `.
2695 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2696 * text; or null for no label
2699 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2700 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2701 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
2703 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
2705 if ( this.label
!== label
) {
2706 if ( this.$label
) {
2707 this.setLabelContent( label
);
2710 this.emit( 'labelChange' );
2719 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2720 * text; or null for no label
2722 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2731 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2732 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
2733 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
2740 * Set the content of the label.
2742 * Do not call this method until after the label element has been set by #setLabelElement.
2745 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2746 * text; or null for no label
2748 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2749 if ( typeof label
=== 'string' ) {
2750 if ( label
.match( /^\s*$/ ) ) {
2751 // Convert whitespace only string to a single non-breaking space
2752 this.$label
.html( ' ' );
2754 this.$label
.text( label
);
2756 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2757 this.$label
.html( label
.toString() );
2758 } else if ( label
instanceof jQuery
) {
2759 this.$label
.empty().append( label
);
2761 this.$label
.empty();
2766 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2767 * additional functionality to an element created by another class. The class provides
2768 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2769 * which are used to customize the look and feel of a widget to better describe its
2770 * importance and functionality.
2772 * The library currently contains the following styling flags for general use:
2774 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2775 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2776 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2778 * The flags affect the appearance of the buttons:
2781 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2782 * var button1 = new OO.ui.ButtonWidget( {
2783 * label: 'Constructive',
2784 * flags: 'constructive'
2786 * var button2 = new OO.ui.ButtonWidget( {
2787 * label: 'Destructive',
2788 * flags: 'destructive'
2790 * var button3 = new OO.ui.ButtonWidget( {
2791 * label: 'Progressive',
2792 * flags: 'progressive'
2794 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2796 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2797 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2805 * @param {Object} [config] Configuration options
2806 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2807 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2808 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2809 * @cfg {jQuery} [$flagged] The flagged element. By default,
2810 * the flagged functionality is applied to the element created by the class ($element).
2811 * If a different element is specified, the flagged functionality will be applied to it instead.
2813 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2814 // Configuration initialization
2815 config
= config
|| {};
2819 this.$flagged
= null;
2822 this.setFlags( config
.flags
);
2823 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2830 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2831 * parameter contains the name of each modified flag and indicates whether it was
2834 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2835 * that the flag was added, `false` that the flag was removed.
2841 * Set the flagged element.
2843 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2844 * If an element is already set, the method will remove the mixin’s effect on that element.
2846 * @param {jQuery} $flagged Element that should be flagged
2848 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2849 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2850 return 'oo-ui-flaggedElement-' + flag
;
2853 if ( this.$flagged
) {
2854 this.$flagged
.removeClass( classNames
);
2857 this.$flagged
= $flagged
.addClass( classNames
);
2861 * Check if the specified flag is set.
2863 * @param {string} flag Name of flag
2864 * @return {boolean} The flag is set
2866 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2867 // This may be called before the constructor, thus before this.flags is set
2868 return this.flags
&& ( flag
in this.flags
);
2872 * Get the names of all flags set.
2874 * @return {string[]} Flag names
2876 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
2877 // This may be called before the constructor, thus before this.flags is set
2878 return Object
.keys( this.flags
|| {} );
2887 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
2888 var flag
, className
,
2891 classPrefix
= 'oo-ui-flaggedElement-';
2893 for ( flag
in this.flags
) {
2894 className
= classPrefix
+ flag
;
2895 changes
[ flag
] = false;
2896 delete this.flags
[ flag
];
2897 remove
.push( className
);
2900 if ( this.$flagged
) {
2901 this.$flagged
.removeClass( remove
.join( ' ' ) );
2904 this.updateThemeClasses();
2905 this.emit( 'flag', changes
);
2911 * Add one or more flags.
2913 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
2914 * or an object keyed by flag name with a boolean value that indicates whether the flag should
2915 * be added (`true`) or removed (`false`).
2919 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
2920 var i
, len
, flag
, className
,
2924 classPrefix
= 'oo-ui-flaggedElement-';
2926 if ( typeof flags
=== 'string' ) {
2927 className
= classPrefix
+ flags
;
2929 if ( !this.flags
[ flags
] ) {
2930 this.flags
[ flags
] = true;
2931 add
.push( className
);
2933 } else if ( Array
.isArray( flags
) ) {
2934 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
2936 className
= classPrefix
+ flag
;
2938 if ( !this.flags
[ flag
] ) {
2939 changes
[ flag
] = true;
2940 this.flags
[ flag
] = true;
2941 add
.push( className
);
2944 } else if ( OO
.isPlainObject( flags
) ) {
2945 for ( flag
in flags
) {
2946 className
= classPrefix
+ flag
;
2947 if ( flags
[ flag
] ) {
2949 if ( !this.flags
[ flag
] ) {
2950 changes
[ flag
] = true;
2951 this.flags
[ flag
] = true;
2952 add
.push( className
);
2956 if ( this.flags
[ flag
] ) {
2957 changes
[ flag
] = false;
2958 delete this.flags
[ flag
];
2959 remove
.push( className
);
2965 if ( this.$flagged
) {
2967 .addClass( add
.join( ' ' ) )
2968 .removeClass( remove
.join( ' ' ) );
2971 this.updateThemeClasses();
2972 this.emit( 'flag', changes
);
2978 * TitledElement is mixed into other classes to provide a `title` attribute.
2979 * Titles are rendered by the browser and are made visible when the user moves
2980 * the mouse over the element. Titles are not visible on touch devices.
2983 * // TitledElement provides a 'title' attribute to the
2984 * // ButtonWidget class
2985 * var button = new OO.ui.ButtonWidget( {
2986 * label: 'Button with Title',
2987 * title: 'I am a button'
2989 * $( 'body' ).append( button.$element );
2995 * @param {Object} [config] Configuration options
2996 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
2997 * If this config is omitted, the title functionality is applied to $element, the
2998 * element created by the class.
2999 * @cfg {string|Function} [title] The title text or a function that returns text. If
3000 * this config is omitted, the value of the {@link #static-title static title} property is used.
3002 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3003 // Configuration initialization
3004 config
= config
|| {};
3007 this.$titled
= null;
3011 this.setTitle( config
.title
|| this.constructor.static.title
);
3012 this.setTitledElement( config
.$titled
|| this.$element
);
3017 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3019 /* Static Properties */
3022 * The title text, a function that returns text, or `null` for no title. The value of the static property
3023 * is overridden if the #title config option is used.
3027 * @property {string|Function|null}
3029 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3034 * Set the titled element.
3036 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3037 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3039 * @param {jQuery} $titled Element that should use the 'titled' functionality
3041 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3042 if ( this.$titled
) {
3043 this.$titled
.removeAttr( 'title' );
3046 this.$titled
= $titled
;
3048 this.$titled
.attr( 'title', this.title
);
3055 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3058 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3059 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3060 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3062 if ( this.title
!== title
) {
3063 if ( this.$titled
) {
3064 if ( title
!== null ) {
3065 this.$titled
.attr( 'title', title
);
3067 this.$titled
.removeAttr( 'title' );
3079 * @return {string} Title string
3081 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3086 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3087 * Accesskeys allow an user to go to a specific element by using
3088 * a shortcut combination of a browser specific keys + the key
3092 * // AccessKeyedElement provides an 'accesskey' attribute to the
3093 * // ButtonWidget class
3094 * var button = new OO.ui.ButtonWidget( {
3095 * label: 'Button with Accesskey',
3098 * $( 'body' ).append( button.$element );
3104 * @param {Object} [config] Configuration options
3105 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3106 * If this config is omitted, the accesskey functionality is applied to $element, the
3107 * element created by the class.
3108 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3109 * this config is omitted, no accesskey will be added.
3111 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3112 // Configuration initialization
3113 config
= config
|| {};
3116 this.$accessKeyed
= null;
3117 this.accessKey
= null;
3120 this.setAccessKey( config
.accessKey
|| null );
3121 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3126 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3128 /* Static Properties */
3131 * The access key, a function that returns a key, or `null` for no accesskey.
3135 * @property {string|Function|null}
3137 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3142 * Set the accesskeyed element.
3144 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3145 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3147 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3149 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3150 if ( this.$accessKeyed
) {
3151 this.$accessKeyed
.removeAttr( 'accesskey' );
3154 this.$accessKeyed
= $accessKeyed
;
3155 if ( this.accessKey
) {
3156 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3163 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
3166 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3167 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3169 if ( this.accessKey
!== accessKey
) {
3170 if ( this.$accessKeyed
) {
3171 if ( accessKey
!== null ) {
3172 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3174 this.$accessKeyed
.removeAttr( 'accesskey' );
3177 this.accessKey
= accessKey
;
3186 * @return {string} accessKey string
3188 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3189 return this.accessKey
;
3193 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3194 * feels, and functionality can be customized via the class’s configuration options
3195 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3198 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3201 * // A button widget
3202 * var button = new OO.ui.ButtonWidget( {
3203 * label: 'Button with Icon',
3205 * iconTitle: 'Remove'
3207 * $( 'body' ).append( button.$element );
3209 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3212 * @extends OO.ui.Widget
3213 * @mixins OO.ui.mixin.ButtonElement
3214 * @mixins OO.ui.mixin.IconElement
3215 * @mixins OO.ui.mixin.IndicatorElement
3216 * @mixins OO.ui.mixin.LabelElement
3217 * @mixins OO.ui.mixin.TitledElement
3218 * @mixins OO.ui.mixin.FlaggedElement
3219 * @mixins OO.ui.mixin.TabIndexedElement
3220 * @mixins OO.ui.mixin.AccessKeyedElement
3223 * @param {Object} [config] Configuration options
3224 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3225 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3226 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3228 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3229 // Configuration initialization
3230 config
= config
|| {};
3232 // Parent constructor
3233 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3235 // Mixin constructors
3236 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3237 OO
.ui
.mixin
.IconElement
.call( this, config
);
3238 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3239 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3240 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3241 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3242 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3243 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3248 this.noFollow
= false;
3251 this.connect( this, { disable
: 'onDisable' } );
3254 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3256 .addClass( 'oo-ui-buttonWidget' )
3257 .append( this.$button
);
3258 this.setHref( config
.href
);
3259 this.setTarget( config
.target
);
3260 this.setNoFollow( config
.noFollow
);
3265 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3266 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3267 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3268 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3269 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3270 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3271 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3272 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3273 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3280 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3281 if ( !this.isDisabled() ) {
3282 // Remove the tab-index while the button is down to prevent the button from stealing focus
3283 this.$button
.removeAttr( 'tabindex' );
3286 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3292 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3293 if ( !this.isDisabled() ) {
3294 // Restore the tab-index after the button is up to restore the button's accessibility
3295 this.$button
.attr( 'tabindex', this.tabIndex
);
3298 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3302 * Get hyperlink location.
3304 * @return {string} Hyperlink location
3306 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3311 * Get hyperlink target.
3313 * @return {string} Hyperlink target
3315 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3320 * Get search engine traversal hint.
3322 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3324 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3325 return this.noFollow
;
3329 * Set hyperlink location.
3331 * @param {string|null} href Hyperlink location, null to remove
3333 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3334 href
= typeof href
=== 'string' ? href
: null;
3335 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3339 if ( href
!== this.href
) {
3348 * Update the `href` attribute, in case of changes to href or
3354 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3355 if ( this.href
!== null && !this.isDisabled() ) {
3356 this.$button
.attr( 'href', this.href
);
3358 this.$button
.removeAttr( 'href' );
3365 * Handle disable events.
3368 * @param {boolean} disabled Element is disabled
3370 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3375 * Set hyperlink target.
3377 * @param {string|null} target Hyperlink target, null to remove
3379 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3380 target
= typeof target
=== 'string' ? target
: null;
3382 if ( target
!== this.target
) {
3383 this.target
= target
;
3384 if ( target
!== null ) {
3385 this.$button
.attr( 'target', target
);
3387 this.$button
.removeAttr( 'target' );
3395 * Set search engine traversal hint.
3397 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3399 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3400 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3402 if ( noFollow
!== this.noFollow
) {
3403 this.noFollow
= noFollow
;
3405 this.$button
.attr( 'rel', 'nofollow' );
3407 this.$button
.removeAttr( 'rel' );
3415 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3416 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3417 * removed, and cleared from the group.
3420 * // Example: A ButtonGroupWidget with two buttons
3421 * var button1 = new OO.ui.PopupButtonWidget( {
3422 * label: 'Select a category',
3425 * $content: $( '<p>List of categories...</p>' ),
3430 * var button2 = new OO.ui.ButtonWidget( {
3433 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3434 * items: [button1, button2]
3436 * $( 'body' ).append( buttonGroup.$element );
3439 * @extends OO.ui.Widget
3440 * @mixins OO.ui.mixin.GroupElement
3443 * @param {Object} [config] Configuration options
3444 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3446 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3447 // Configuration initialization
3448 config
= config
|| {};
3450 // Parent constructor
3451 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3453 // Mixin constructors
3454 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3457 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3458 if ( Array
.isArray( config
.items
) ) {
3459 this.addItems( config
.items
);
3465 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3466 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3469 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3470 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3471 * for a list of icons included in the library.
3474 * // An icon widget with a label
3475 * var myIcon = new OO.ui.IconWidget( {
3479 * // Create a label.
3480 * var iconLabel = new OO.ui.LabelWidget( {
3483 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3485 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3488 * @extends OO.ui.Widget
3489 * @mixins OO.ui.mixin.IconElement
3490 * @mixins OO.ui.mixin.TitledElement
3491 * @mixins OO.ui.mixin.FlaggedElement
3494 * @param {Object} [config] Configuration options
3496 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3497 // Configuration initialization
3498 config
= config
|| {};
3500 // Parent constructor
3501 OO
.ui
.IconWidget
.parent
.call( this, config
);
3503 // Mixin constructors
3504 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3505 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3506 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3509 this.$element
.addClass( 'oo-ui-iconWidget' );
3514 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3515 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3516 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3517 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3519 /* Static Properties */
3521 OO
.ui
.IconWidget
.static.tagName
= 'span';
3524 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3525 * attention to the status of an item or to clarify the function of a control. For a list of
3526 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3529 * // Example of an indicator widget
3530 * var indicator1 = new OO.ui.IndicatorWidget( {
3531 * indicator: 'alert'
3534 * // Create a fieldset layout to add a label
3535 * var fieldset = new OO.ui.FieldsetLayout();
3536 * fieldset.addItems( [
3537 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3539 * $( 'body' ).append( fieldset.$element );
3541 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3544 * @extends OO.ui.Widget
3545 * @mixins OO.ui.mixin.IndicatorElement
3546 * @mixins OO.ui.mixin.TitledElement
3549 * @param {Object} [config] Configuration options
3551 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3552 // Configuration initialization
3553 config
= config
|| {};
3555 // Parent constructor
3556 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3558 // Mixin constructors
3559 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3560 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3563 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3568 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3569 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3570 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3572 /* Static Properties */
3574 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3577 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3578 * be configured with a `label` option that is set to a string, a label node, or a function:
3580 * - String: a plaintext string
3581 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3582 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3583 * - Function: a function that will produce a string in the future. Functions are used
3584 * in cases where the value of the label is not currently defined.
3586 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3587 * will come into focus when the label is clicked.
3590 * // Examples of LabelWidgets
3591 * var label1 = new OO.ui.LabelWidget( {
3592 * label: 'plaintext label'
3594 * var label2 = new OO.ui.LabelWidget( {
3595 * label: $( '<a href="default.html">jQuery label</a>' )
3597 * // Create a fieldset layout with fields for each example
3598 * var fieldset = new OO.ui.FieldsetLayout();
3599 * fieldset.addItems( [
3600 * new OO.ui.FieldLayout( label1 ),
3601 * new OO.ui.FieldLayout( label2 )
3603 * $( 'body' ).append( fieldset.$element );
3606 * @extends OO.ui.Widget
3607 * @mixins OO.ui.mixin.LabelElement
3610 * @param {Object} [config] Configuration options
3611 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3612 * Clicking the label will focus the specified input field.
3614 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3615 // Configuration initialization
3616 config
= config
|| {};
3618 // Parent constructor
3619 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3621 // Mixin constructors
3622 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3623 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3626 this.input
= config
.input
;
3629 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3630 this.$element
.on( 'click', this.onClick
.bind( this ) );
3634 this.$element
.addClass( 'oo-ui-labelWidget' );
3639 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3640 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3641 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3643 /* Static Properties */
3645 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3650 * Handles label mouse click events.
3653 * @param {jQuery.Event} e Mouse click event
3655 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3656 this.input
.simulateLabelClick();
3661 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3662 * and that they should wait before proceeding. The pending state is visually represented with a pending
3663 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3664 * field of a {@link OO.ui.TextInputWidget text input widget}.
3666 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3667 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3668 * in process dialogs.
3671 * function MessageDialog( config ) {
3672 * MessageDialog.parent.call( this, config );
3674 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3676 * MessageDialog.static.actions = [
3677 * { action: 'save', label: 'Done', flags: 'primary' },
3678 * { label: 'Cancel', flags: 'safe' }
3681 * MessageDialog.prototype.initialize = function () {
3682 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3683 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3684 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
3685 * this.$body.append( this.content.$element );
3687 * MessageDialog.prototype.getBodyHeight = function () {
3690 * MessageDialog.prototype.getActionProcess = function ( action ) {
3691 * var dialog = this;
3692 * if ( action === 'save' ) {
3693 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3694 * return new OO.ui.Process()
3696 * .next( function () {
3697 * dialog.getActions().get({actions: 'save'})[0].popPending();
3700 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3703 * var windowManager = new OO.ui.WindowManager();
3704 * $( 'body' ).append( windowManager.$element );
3706 * var dialog = new MessageDialog();
3707 * windowManager.addWindows( [ dialog ] );
3708 * windowManager.openWindow( dialog );
3714 * @param {Object} [config] Configuration options
3715 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3717 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3718 // Configuration initialization
3719 config
= config
|| {};
3723 this.$pending
= null;
3726 this.setPendingElement( config
.$pending
|| this.$element
);
3731 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3736 * Set the pending element (and clean up any existing one).
3738 * @param {jQuery} $pending The element to set to pending.
3740 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3741 if ( this.$pending
) {
3742 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3745 this.$pending
= $pending
;
3746 if ( this.pending
> 0 ) {
3747 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3752 * Check if an element is pending.
3754 * @return {boolean} Element is pending
3756 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3757 return !!this.pending
;
3761 * Increase the pending counter. The pending state will remain active until the counter is zero
3762 * (i.e., the number of calls to #pushPending and #popPending is the same).
3766 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3767 if ( this.pending
=== 0 ) {
3768 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3769 this.updateThemeClasses();
3777 * Decrease the pending counter. The pending state will remain active until the counter is zero
3778 * (i.e., the number of calls to #pushPending and #popPending is the same).
3782 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3783 if ( this.pending
=== 1 ) {
3784 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3785 this.updateThemeClasses();
3787 this.pending
= Math
.max( 0, this.pending
- 1 );
3793 * Element that can be automatically clipped to visible boundaries.
3795 * Whenever the element's natural height changes, you have to call
3796 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3797 * clipping correctly.
3799 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3800 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3801 * then #$clippable will be given a fixed reduced height and/or width and will be made
3802 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3803 * but you can build a static footer by setting #$clippableContainer to an element that contains
3804 * #$clippable and the footer.
3810 * @param {Object} [config] Configuration options
3811 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3812 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3813 * omit to use #$clippable
3815 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3816 // Configuration initialization
3817 config
= config
|| {};
3820 this.$clippable
= null;
3821 this.$clippableContainer
= null;
3822 this.clipping
= false;
3823 this.clippedHorizontally
= false;
3824 this.clippedVertically
= false;
3825 this.$clippableScrollableContainer
= null;
3826 this.$clippableScroller
= null;
3827 this.$clippableWindow
= null;
3828 this.idealWidth
= null;
3829 this.idealHeight
= null;
3830 this.onClippableScrollHandler
= this.clip
.bind( this );
3831 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3834 if ( config
.$clippableContainer
) {
3835 this.setClippableContainer( config
.$clippableContainer
);
3837 this.setClippableElement( config
.$clippable
|| this.$element
);
3843 * Set clippable element.
3845 * If an element is already set, it will be cleaned up before setting up the new element.
3847 * @param {jQuery} $clippable Element to make clippable
3849 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3850 if ( this.$clippable
) {
3851 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3852 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3853 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3856 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3861 * Set clippable container.
3863 * This is the container that will be measured when deciding whether to clip. When clipping,
3864 * #$clippable will be resized in order to keep the clippable container fully visible.
3866 * If the clippable container is unset, #$clippable will be used.
3868 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
3870 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
3871 this.$clippableContainer
= $clippableContainer
;
3872 if ( this.$clippable
) {
3880 * Do not turn clipping on until after the element is attached to the DOM and visible.
3882 * @param {boolean} [clipping] Enable clipping, omit to toggle
3885 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
3886 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
3888 if ( this.clipping
!== clipping
) {
3889 this.clipping
= clipping
;
3891 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
3892 // If the clippable container is the root, we have to listen to scroll events and check
3893 // jQuery.scrollTop on the window because of browser inconsistencies
3894 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
3895 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
3896 this.$clippableScrollableContainer
;
3897 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
3898 this.$clippableWindow
= $( this.getElementWindow() )
3899 .on( 'resize', this.onClippableWindowResizeHandler
);
3900 // Initial clip after visible
3903 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3904 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3906 this.$clippableScrollableContainer
= null;
3907 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
3908 this.$clippableScroller
= null;
3909 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
3910 this.$clippableWindow
= null;
3918 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
3920 * @return {boolean} Element will be clipped to the visible area
3922 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
3923 return this.clipping
;
3927 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
3929 * @return {boolean} Part of the element is being clipped
3931 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
3932 return this.clippedHorizontally
|| this.clippedVertically
;
3936 * Check if the right of the element is being clipped by the nearest scrollable container.
3938 * @return {boolean} Part of the element is being clipped
3940 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
3941 return this.clippedHorizontally
;
3945 * Check if the bottom of the element is being clipped by the nearest scrollable container.
3947 * @return {boolean} Part of the element is being clipped
3949 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
3950 return this.clippedVertically
;
3954 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
3956 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
3957 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
3959 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
3960 this.idealWidth
= width
;
3961 this.idealHeight
= height
;
3963 if ( !this.clipping
) {
3964 // Update dimensions
3965 this.$clippable
.css( { width
: width
, height
: height
} );
3967 // While clipping, idealWidth and idealHeight are not considered
3971 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
3972 * the element's natural height changes.
3974 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
3975 * overlapped by, the visible area of the nearest scrollable container.
3979 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
3980 var $container
, extraHeight
, extraWidth
, ccOffset
,
3981 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
3982 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
3983 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
3984 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
3985 buffer
= 7; // Chosen by fair dice roll
3987 if ( !this.clipping
) {
3988 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
3992 $container
= this.$clippableContainer
|| this.$clippable
;
3993 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
3994 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
3995 ccOffset
= $container
.offset();
3996 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
3997 this.$clippableWindow
: this.$clippableScrollableContainer
;
3998 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
3999 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4000 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4001 ccWidth
= $container
.outerWidth() + buffer
;
4002 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4003 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4004 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4005 desiredWidth
= ccOffset
.left
< 0 ?
4006 ccWidth
+ ccOffset
.left
:
4007 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4008 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4009 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4010 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4011 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4012 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4013 clipWidth
= allotedWidth
< naturalWidth
;
4014 clipHeight
= allotedHeight
< naturalHeight
;
4017 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
4019 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
4022 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
4024 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
4027 // If we stopped clipping in at least one of the dimensions
4028 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4029 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4032 this.clippedHorizontally
= clipWidth
;
4033 this.clippedVertically
= clipHeight
;
4039 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4040 * By default, each popup has an anchor that points toward its origin.
4041 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4044 * // A popup widget.
4045 * var popup = new OO.ui.PopupWidget( {
4046 * $content: $( '<p>Hi there!</p>' ),
4051 * $( 'body' ).append( popup.$element );
4052 * // To display the popup, toggle the visibility to 'true'.
4053 * popup.toggle( true );
4055 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4058 * @extends OO.ui.Widget
4059 * @mixins OO.ui.mixin.LabelElement
4060 * @mixins OO.ui.mixin.ClippableElement
4063 * @param {Object} [config] Configuration options
4064 * @cfg {number} [width=320] Width of popup in pixels
4065 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4066 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4067 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4068 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4069 * popup is leaning towards the right of the screen.
4070 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4071 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4072 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4073 * sentence in the given language.
4074 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4075 * See the [OOjs UI docs on MediaWiki][3] for an example.
4076 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4077 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4078 * @cfg {jQuery} [$content] Content to append to the popup's body
4079 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4080 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4081 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4082 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4084 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4085 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
4087 * @cfg {boolean} [padded] Add padding to the popup's body
4089 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4090 // Configuration initialization
4091 config
= config
|| {};
4093 // Parent constructor
4094 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4096 // Properties (must be set before ClippableElement constructor call)
4097 this.$body
= $( '<div>' );
4098 this.$popup
= $( '<div>' );
4100 // Mixin constructors
4101 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4102 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4103 $clippable
: this.$body
,
4104 $clippableContainer
: this.$popup
4108 this.$head
= $( '<div>' );
4109 this.$footer
= $( '<div>' );
4110 this.$anchor
= $( '<div>' );
4111 // If undefined, will be computed lazily in updateDimensions()
4112 this.$container
= config
.$container
;
4113 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4114 this.autoClose
= !!config
.autoClose
;
4115 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4116 this.transitionTimeout
= null;
4118 this.width
= config
.width
!== undefined ? config
.width
: 320;
4119 this.height
= config
.height
!== undefined ? config
.height
: null;
4120 this.setAlignment( config
.align
);
4121 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4122 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4123 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4126 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4129 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4130 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4131 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4133 .addClass( 'oo-ui-popupWidget-head' )
4134 .append( this.$label
, this.closeButton
.$element
);
4135 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
4136 if ( !config
.head
) {
4137 this.$head
.addClass( 'oo-ui-element-hidden' );
4139 if ( !config
.$footer
) {
4140 this.$footer
.addClass( 'oo-ui-element-hidden' );
4143 .addClass( 'oo-ui-popupWidget-popup' )
4144 .append( this.$head
, this.$body
, this.$footer
);
4146 .addClass( 'oo-ui-popupWidget' )
4147 .append( this.$popup
, this.$anchor
);
4148 // Move content, which was added to #$element by OO.ui.Widget, to the body
4149 if ( config
.$content
instanceof jQuery
) {
4150 this.$body
.append( config
.$content
);
4152 if ( config
.$footer
instanceof jQuery
) {
4153 this.$footer
.append( config
.$footer
);
4155 if ( config
.padded
) {
4156 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4159 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4160 // that reference properties not initialized at that time of parent class construction
4161 // TODO: Find a better way to handle post-constructor setup
4162 this.visible
= false;
4163 this.$element
.addClass( 'oo-ui-element-hidden' );
4168 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4169 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4170 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4175 * Handles mouse down events.
4178 * @param {MouseEvent} e Mouse down event
4180 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4183 !$.contains( this.$element
[ 0 ], e
.target
) &&
4184 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4186 this.toggle( false );
4191 * Bind mouse down listener.
4195 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4196 // Capture clicks outside popup
4197 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4201 * Handles close button click events.
4205 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4206 if ( this.isVisible() ) {
4207 this.toggle( false );
4212 * Unbind mouse down listener.
4216 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4217 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4221 * Handles key down events.
4224 * @param {KeyboardEvent} e Key down event
4226 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4228 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4231 this.toggle( false );
4233 e
.stopPropagation();
4238 * Bind key down listener.
4242 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4243 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4247 * Unbind key down listener.
4251 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4252 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4256 * Show, hide, or toggle the visibility of the anchor.
4258 * @param {boolean} [show] Show anchor, omit to toggle
4260 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4261 show
= show
=== undefined ? !this.anchored
: !!show
;
4263 if ( this.anchored
!== show
) {
4265 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4267 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4269 this.anchored
= show
;
4274 * Check if the anchor is visible.
4276 * @return {boolean} Anchor is visible
4278 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4285 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4287 show
= show
=== undefined ? !this.isVisible() : !!show
;
4289 change
= show
!== this.isVisible();
4292 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4296 if ( this.autoClose
) {
4297 this.bindMouseDownListener();
4298 this.bindKeyDownListener();
4300 this.updateDimensions();
4301 this.toggleClipping( true );
4303 this.toggleClipping( false );
4304 if ( this.autoClose
) {
4305 this.unbindMouseDownListener();
4306 this.unbindKeyDownListener();
4315 * Set the size of the popup.
4317 * Changing the size may also change the popup's position depending on the alignment.
4319 * @param {number} width Width in pixels
4320 * @param {number} height Height in pixels
4321 * @param {boolean} [transition=false] Use a smooth transition
4324 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4326 this.height
= height
!== undefined ? height
: null;
4327 if ( this.isVisible() ) {
4328 this.updateDimensions( transition
);
4333 * Update the size and position.
4335 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4336 * be called automatically.
4338 * @param {boolean} [transition=false] Use a smooth transition
4341 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4342 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4343 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4347 if ( !this.$container
) {
4348 // Lazy-initialize $container if not specified in constructor
4349 this.$container
= $( this.getClosestScrollableElementContainer() );
4352 // Set height and width before measuring things, since it might cause our measurements
4353 // to change (e.g. due to scrollbars appearing or disappearing)
4356 height
: this.height
!== null ? this.height
: 'auto'
4359 // If we are in RTL, we need to flip the alignment, unless it is center
4360 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4361 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4362 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4364 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4369 // Compute initial popupOffset based on alignment
4370 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4372 // Figure out if this will cause the popup to go beyond the edge of the container
4373 originOffset
= this.$element
.offset().left
;
4374 containerLeft
= this.$container
.offset().left
;
4375 containerWidth
= this.$container
.innerWidth();
4376 containerRight
= containerLeft
+ containerWidth
;
4377 popupLeft
= popupOffset
- this.containerPadding
;
4378 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4379 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4380 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4382 // Adjust offset to make the popup not go beyond the edge, if needed
4383 if ( overlapRight
< 0 ) {
4384 popupOffset
+= overlapRight
;
4385 } else if ( overlapLeft
< 0 ) {
4386 popupOffset
-= overlapLeft
;
4389 // Adjust offset to avoid anchor being rendered too close to the edge
4390 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4391 // TODO: Find a measurement that works for CSS anchors and image anchors
4392 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4393 if ( popupOffset
+ this.width
< anchorWidth
) {
4394 popupOffset
= anchorWidth
- this.width
;
4395 } else if ( -popupOffset
< anchorWidth
) {
4396 popupOffset
= -anchorWidth
;
4399 // Prevent transition from being interrupted
4400 clearTimeout( this.transitionTimeout
);
4402 // Enable transition
4403 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4406 // Position body relative to anchor
4407 this.$popup
.css( 'margin-left', popupOffset
);
4410 // Prevent transitioning after transition is complete
4411 this.transitionTimeout
= setTimeout( function () {
4412 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4415 // Prevent transitioning immediately
4416 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4419 // Reevaluate clipping state since we've relocated and resized the popup
4426 * Set popup alignment
4427 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4428 * `backwards` or `forwards`.
4430 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4431 // Validate alignment and transform deprecated values
4432 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4433 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4435 this.align
= 'center';
4440 * Get popup alignment
4441 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4442 * `backwards` or `forwards`.
4444 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4449 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4450 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4451 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4452 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4458 * @param {Object} [config] Configuration options
4459 * @cfg {Object} [popup] Configuration to pass to popup
4460 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4462 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4463 // Configuration initialization
4464 config
= config
|| {};
4467 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4468 { autoClose
: true },
4470 { $autoCloseIgnore
: this.$element
}
4479 * @return {OO.ui.PopupWidget} Popup widget
4481 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4486 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4487 * which is used to display additional information or options.
4490 * // Example of a popup button.
4491 * var popupButton = new OO.ui.PopupButtonWidget( {
4492 * label: 'Popup button with options',
4495 * $content: $( '<p>Additional options here.</p>' ),
4497 * align: 'force-left'
4500 * // Append the button to the DOM.
4501 * $( 'body' ).append( popupButton.$element );
4504 * @extends OO.ui.ButtonWidget
4505 * @mixins OO.ui.mixin.PopupElement
4508 * @param {Object} [config] Configuration options
4510 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4511 // Parent constructor
4512 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4514 // Mixin constructors
4515 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4518 this.connect( this, { click
: 'onAction' } );
4522 .addClass( 'oo-ui-popupButtonWidget' )
4523 .attr( 'aria-haspopup', 'true' )
4524 .append( this.popup
.$element
);
4529 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4530 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4535 * Handle the button action being triggered.
4539 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4540 this.popup
.toggle();
4544 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4546 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4551 * @extends OO.ui.mixin.GroupElement
4554 * @param {Object} [config] Configuration options
4556 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4557 // Parent constructor
4558 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
4563 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4568 * Set the disabled state of the widget.
4570 * This will also update the disabled state of child widgets.
4572 * @param {boolean} disabled Disable widget
4575 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4579 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4580 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4582 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4584 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4585 this.items
[ i
].updateDisabled();
4593 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4595 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4596 * allows bidirectional communication.
4598 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4606 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4613 * Check if widget is disabled.
4615 * Checks parent if present, making disabled state inheritable.
4617 * @return {boolean} Widget is disabled
4619 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4620 return this.disabled
||
4621 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4625 * Set group element is in.
4627 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4630 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4632 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4633 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4635 // Initialize item disabled states
4636 this.updateDisabled();
4642 * OptionWidgets are special elements that can be selected and configured with data. The
4643 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4644 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4645 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4647 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4650 * @extends OO.ui.Widget
4651 * @mixins OO.ui.mixin.LabelElement
4652 * @mixins OO.ui.mixin.FlaggedElement
4655 * @param {Object} [config] Configuration options
4657 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4658 // Configuration initialization
4659 config
= config
|| {};
4661 // Parent constructor
4662 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4664 // Mixin constructors
4665 OO
.ui
.mixin
.ItemWidget
.call( this );
4666 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4667 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4670 this.selected
= false;
4671 this.highlighted
= false;
4672 this.pressed
= false;
4676 .data( 'oo-ui-optionWidget', this )
4677 .attr( 'role', 'option' )
4678 .attr( 'aria-selected', 'false' )
4679 .addClass( 'oo-ui-optionWidget' )
4680 .append( this.$label
);
4685 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4686 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4687 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4688 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4690 /* Static Properties */
4692 OO
.ui
.OptionWidget
.static.selectable
= true;
4694 OO
.ui
.OptionWidget
.static.highlightable
= true;
4696 OO
.ui
.OptionWidget
.static.pressable
= true;
4698 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4703 * Check if the option can be selected.
4705 * @return {boolean} Item is selectable
4707 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4708 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4712 * Check if the option can be highlighted. A highlight indicates that the option
4713 * may be selected when a user presses enter or clicks. Disabled items cannot
4716 * @return {boolean} Item is highlightable
4718 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4719 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4723 * Check if the option can be pressed. The pressed state occurs when a user mouses
4724 * down on an item, but has not yet let go of the mouse.
4726 * @return {boolean} Item is pressable
4728 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4729 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4733 * Check if the option is selected.
4735 * @return {boolean} Item is selected
4737 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4738 return this.selected
;
4742 * Check if the option is highlighted. A highlight indicates that the
4743 * item may be selected when a user presses enter or clicks.
4745 * @return {boolean} Item is highlighted
4747 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4748 return this.highlighted
;
4752 * Check if the option is pressed. The pressed state occurs when a user mouses
4753 * down on an item, but has not yet let go of the mouse. The item may appear
4754 * selected, but it will not be selected until the user releases the mouse.
4756 * @return {boolean} Item is pressed
4758 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4759 return this.pressed
;
4763 * Set the option’s selected state. In general, all modifications to the selection
4764 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4765 * method instead of this method.
4767 * @param {boolean} [state=false] Select option
4770 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4771 if ( this.constructor.static.selectable
) {
4772 this.selected
= !!state
;
4774 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4775 .attr( 'aria-selected', state
.toString() );
4776 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4777 this.scrollElementIntoView();
4779 this.updateThemeClasses();
4785 * Set the option’s highlighted state. In general, all programmatic
4786 * modifications to the highlight should be handled by the
4787 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4788 * method instead of this method.
4790 * @param {boolean} [state=false] Highlight option
4793 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4794 if ( this.constructor.static.highlightable
) {
4795 this.highlighted
= !!state
;
4796 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4797 this.updateThemeClasses();
4803 * Set the option’s pressed state. In general, all
4804 * programmatic modifications to the pressed state should be handled by the
4805 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4806 * method instead of this method.
4808 * @param {boolean} [state=false] Press option
4811 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4812 if ( this.constructor.static.pressable
) {
4813 this.pressed
= !!state
;
4814 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4815 this.updateThemeClasses();
4821 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4822 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4823 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4826 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4827 * information, please see the [OOjs UI documentation on MediaWiki][1].
4830 * // Example of a select widget with three options
4831 * var select = new OO.ui.SelectWidget( {
4833 * new OO.ui.OptionWidget( {
4835 * label: 'Option One',
4837 * new OO.ui.OptionWidget( {
4839 * label: 'Option Two',
4841 * new OO.ui.OptionWidget( {
4843 * label: 'Option Three',
4847 * $( 'body' ).append( select.$element );
4849 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4853 * @extends OO.ui.Widget
4854 * @mixins OO.ui.mixin.GroupWidget
4857 * @param {Object} [config] Configuration options
4858 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
4859 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
4860 * the [OOjs UI documentation on MediaWiki] [2] for examples.
4861 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4863 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
4864 // Configuration initialization
4865 config
= config
|| {};
4867 // Parent constructor
4868 OO
.ui
.SelectWidget
.parent
.call( this, config
);
4870 // Mixin constructors
4871 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
4874 this.pressed
= false;
4875 this.selecting
= null;
4876 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4877 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
4878 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4879 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4880 this.keyPressBuffer
= '';
4881 this.keyPressBufferTimer
= null;
4884 this.connect( this, {
4888 mousedown
: this.onMouseDown
.bind( this ),
4889 mouseover
: this.onMouseOver
.bind( this ),
4890 mouseleave
: this.onMouseLeave
.bind( this )
4895 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
4896 .attr( 'role', 'listbox' );
4897 if ( Array
.isArray( config
.items
) ) {
4898 this.addItems( config
.items
);
4904 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
4906 // Need to mixin base class as well
4907 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
4908 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
4911 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
4920 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
4922 * @param {OO.ui.OptionWidget|null} item Highlighted item
4928 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
4929 * pressed state of an option.
4931 * @param {OO.ui.OptionWidget|null} item Pressed item
4937 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
4939 * @param {OO.ui.OptionWidget|null} item Selected item
4944 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
4945 * @param {OO.ui.OptionWidget} item Chosen item
4951 * An `add` event is emitted when options are added to the select with the #addItems method.
4953 * @param {OO.ui.OptionWidget[]} items Added items
4954 * @param {number} index Index of insertion point
4960 * A `remove` event is emitted when options are removed from the select with the #clearItems
4961 * or #removeItems methods.
4963 * @param {OO.ui.OptionWidget[]} items Removed items
4969 * Handle mouse down events.
4972 * @param {jQuery.Event} e Mouse down event
4974 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
4977 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
4978 this.togglePressed( true );
4979 item
= this.getTargetItem( e
);
4980 if ( item
&& item
.isSelectable() ) {
4981 this.pressItem( item
);
4982 this.selecting
= item
;
4983 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4984 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
4991 * Handle mouse up events.
4994 * @param {MouseEvent} e Mouse up event
4996 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
4999 this.togglePressed( false );
5000 if ( !this.selecting
) {
5001 item
= this.getTargetItem( e
);
5002 if ( item
&& item
.isSelectable() ) {
5003 this.selecting
= item
;
5006 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5007 this.pressItem( null );
5008 this.chooseItem( this.selecting
);
5009 this.selecting
= null;
5012 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5013 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5019 * Handle mouse move events.
5022 * @param {MouseEvent} e Mouse move event
5024 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5027 if ( !this.isDisabled() && this.pressed
) {
5028 item
= this.getTargetItem( e
);
5029 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5030 this.pressItem( item
);
5031 this.selecting
= item
;
5037 * Handle mouse over events.
5040 * @param {jQuery.Event} e Mouse over event
5042 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5045 if ( !this.isDisabled() ) {
5046 item
= this.getTargetItem( e
);
5047 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5053 * Handle mouse leave events.
5056 * @param {jQuery.Event} e Mouse over event
5058 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5059 if ( !this.isDisabled() ) {
5060 this.highlightItem( null );
5066 * Handle key down events.
5069 * @param {KeyboardEvent} e Key down event
5071 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5074 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5076 if ( !this.isDisabled() && this.isVisible() ) {
5077 switch ( e
.keyCode
) {
5078 case OO
.ui
.Keys
.ENTER
:
5079 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5080 // Was only highlighted, now let's select it. No-op if already selected.
5081 this.chooseItem( currentItem
);
5086 case OO
.ui
.Keys
.LEFT
:
5087 this.clearKeyPressBuffer();
5088 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5091 case OO
.ui
.Keys
.DOWN
:
5092 case OO
.ui
.Keys
.RIGHT
:
5093 this.clearKeyPressBuffer();
5094 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5097 case OO
.ui
.Keys
.ESCAPE
:
5098 case OO
.ui
.Keys
.TAB
:
5099 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5100 currentItem
.setHighlighted( false );
5102 this.unbindKeyDownListener();
5103 this.unbindKeyPressListener();
5104 // Don't prevent tabbing away / defocusing
5110 if ( nextItem
.constructor.static.highlightable
) {
5111 this.highlightItem( nextItem
);
5113 this.chooseItem( nextItem
);
5115 nextItem
.scrollElementIntoView();
5120 e
.stopPropagation();
5126 * Bind key down listener.
5130 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5131 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5135 * Unbind key down listener.
5139 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5140 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5144 * Clear the key-press buffer
5148 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5149 if ( this.keyPressBufferTimer
) {
5150 clearTimeout( this.keyPressBufferTimer
);
5151 this.keyPressBufferTimer
= null;
5153 this.keyPressBuffer
= '';
5157 * Handle key press events.
5160 * @param {KeyboardEvent} e Key press event
5162 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5163 var c
, filter
, item
;
5165 if ( !e
.charCode
) {
5166 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5167 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5172 if ( String
.fromCodePoint
) {
5173 c
= String
.fromCodePoint( e
.charCode
);
5175 c
= String
.fromCharCode( e
.charCode
);
5178 if ( this.keyPressBufferTimer
) {
5179 clearTimeout( this.keyPressBufferTimer
);
5181 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5183 item
= this.getHighlightedItem() || this.getSelectedItem();
5185 if ( this.keyPressBuffer
=== c
) {
5186 // Common (if weird) special case: typing "xxxx" will cycle through all
5187 // the items beginning with "x".
5189 item
= this.getRelativeSelectableItem( item
, 1 );
5192 this.keyPressBuffer
+= c
;
5195 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5196 if ( !item
|| !filter( item
) ) {
5197 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5200 if ( item
.constructor.static.highlightable
) {
5201 this.highlightItem( item
);
5203 this.chooseItem( item
);
5205 item
.scrollElementIntoView();
5209 e
.stopPropagation();
5213 * Get a matcher for the specific string
5216 * @param {string} s String to match against items
5217 * @param {boolean} [exact=false] Only accept exact matches
5218 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5220 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5223 if ( s
.normalize
) {
5226 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5227 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5231 re
= new RegExp( re
, 'i' );
5232 return function ( item
) {
5233 var l
= item
.getLabel();
5234 if ( typeof l
!== 'string' ) {
5235 l
= item
.$label
.text();
5237 if ( l
.normalize
) {
5240 return re
.test( l
);
5245 * Bind key press listener.
5249 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5250 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5254 * Unbind key down listener.
5256 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5261 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5262 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5263 this.clearKeyPressBuffer();
5267 * Visibility change handler
5270 * @param {boolean} visible
5272 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5274 this.clearKeyPressBuffer();
5279 * Get the closest item to a jQuery.Event.
5282 * @param {jQuery.Event} e
5283 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5285 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5286 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5290 * Get selected item.
5292 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5294 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5297 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5298 if ( this.items
[ i
].isSelected() ) {
5299 return this.items
[ i
];
5306 * Get highlighted item.
5308 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5310 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5313 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5314 if ( this.items
[ i
].isHighlighted() ) {
5315 return this.items
[ i
];
5322 * Toggle pressed state.
5324 * Press is a state that occurs when a user mouses down on an item, but
5325 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5326 * until the user releases the mouse.
5328 * @param {boolean} pressed An option is being pressed
5330 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5331 if ( pressed
=== undefined ) {
5332 pressed
= !this.pressed
;
5334 if ( pressed
!== this.pressed
) {
5336 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5337 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5338 this.pressed
= pressed
;
5343 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5344 * and any existing highlight will be removed. The highlight is mutually exclusive.
5346 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5350 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5351 var i
, len
, highlighted
,
5354 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5355 highlighted
= this.items
[ i
] === item
;
5356 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5357 this.items
[ i
].setHighlighted( highlighted
);
5362 this.emit( 'highlight', item
);
5369 * Fetch an item by its label.
5371 * @param {string} label Label of the item to select.
5372 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5373 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5375 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5377 len
= this.items
.length
,
5378 filter
= this.getItemMatcher( label
, true );
5380 for ( i
= 0; i
< len
; i
++ ) {
5381 item
= this.items
[ i
];
5382 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5389 filter
= this.getItemMatcher( label
, false );
5390 for ( i
= 0; i
< len
; i
++ ) {
5391 item
= this.items
[ i
];
5392 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5408 * Programmatically select an option by its label. If the item does not exist,
5409 * all options will be deselected.
5411 * @param {string} [label] Label of the item to select.
5412 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5416 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5417 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5418 if ( label
=== undefined || !itemFromLabel
) {
5419 return this.selectItem();
5421 return this.selectItem( itemFromLabel
);
5425 * Programmatically select an option by its data. If the `data` parameter is omitted,
5426 * or if the item does not exist, all options will be deselected.
5428 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5432 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5433 var itemFromData
= this.getItemFromData( data
);
5434 if ( data
=== undefined || !itemFromData
) {
5435 return this.selectItem();
5437 return this.selectItem( itemFromData
);
5441 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5442 * all options will be deselected.
5444 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5448 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5449 var i
, len
, selected
,
5452 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5453 selected
= this.items
[ i
] === item
;
5454 if ( this.items
[ i
].isSelected() !== selected
) {
5455 this.items
[ i
].setSelected( selected
);
5460 this.emit( 'select', item
);
5469 * Press is a state that occurs when a user mouses down on an item, but has not
5470 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5471 * releases the mouse.
5473 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5477 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5478 var i
, len
, pressed
,
5481 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5482 pressed
= this.items
[ i
] === item
;
5483 if ( this.items
[ i
].isPressed() !== pressed
) {
5484 this.items
[ i
].setPressed( pressed
);
5489 this.emit( 'press', item
);
5498 * Note that ‘choose’ should never be modified programmatically. A user can choose
5499 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5500 * use the #selectItem method.
5502 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5503 * when users choose an item with the keyboard or mouse.
5505 * @param {OO.ui.OptionWidget} item Item to choose
5509 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5511 this.selectItem( item
);
5512 this.emit( 'choose', item
);
5519 * Get an option by its position relative to the specified item (or to the start of the option array,
5520 * if item is `null`). The direction in which to search through the option array is specified with a
5521 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5522 * `null` if there are no options in the array.
5524 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5525 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5526 * @param {Function} filter Only consider items for which this function returns
5527 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5528 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5530 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5531 var currentIndex
, nextIndex
, i
,
5532 increase
= direction
> 0 ? 1 : -1,
5533 len
= this.items
.length
;
5535 if ( !$.isFunction( filter
) ) {
5536 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
5539 if ( item
instanceof OO
.ui
.OptionWidget
) {
5540 currentIndex
= this.items
.indexOf( item
);
5541 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5543 // If no item is selected and moving forward, start at the beginning.
5544 // If moving backward, start at the end.
5545 nextIndex
= direction
> 0 ? 0 : len
- 1;
5548 for ( i
= 0; i
< len
; i
++ ) {
5549 item
= this.items
[ nextIndex
];
5550 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5553 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5559 * Get the next selectable item or `null` if there are no selectable items.
5560 * Disabled options and menu-section markers and breaks are not selectable.
5562 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5564 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5567 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5568 item
= this.items
[ i
];
5569 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
5578 * Add an array of options to the select. Optionally, an index number can be used to
5579 * specify an insertion point.
5581 * @param {OO.ui.OptionWidget[]} items Items to add
5582 * @param {number} [index] Index to insert items after
5586 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5588 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5590 // Always provide an index, even if it was omitted
5591 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5597 * Remove the specified array of options from the select. Options will be detached
5598 * from the DOM, not removed, so they can be reused later. To remove all options from
5599 * the select, you may wish to use the #clearItems method instead.
5601 * @param {OO.ui.OptionWidget[]} items Items to remove
5605 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5608 // Deselect items being removed
5609 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5611 if ( item
.isSelected() ) {
5612 this.selectItem( null );
5617 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5619 this.emit( 'remove', items
);
5625 * Clear all options from the select. Options will be detached from the DOM, not removed,
5626 * so that they can be reused later. To remove a subset of options from the select, use
5627 * the #removeItems method.
5632 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5633 var items
= this.items
.slice();
5636 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5639 this.selectItem( null );
5641 this.emit( 'remove', items
);
5647 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5648 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5649 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5650 * options. For more information about options and selects, please see the
5651 * [OOjs UI documentation on MediaWiki][1].
5654 * // Decorated options in a select widget
5655 * var select = new OO.ui.SelectWidget( {
5657 * new OO.ui.DecoratedOptionWidget( {
5659 * label: 'Option with icon',
5662 * new OO.ui.DecoratedOptionWidget( {
5664 * label: 'Option with indicator',
5669 * $( 'body' ).append( select.$element );
5671 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5674 * @extends OO.ui.OptionWidget
5675 * @mixins OO.ui.mixin.IconElement
5676 * @mixins OO.ui.mixin.IndicatorElement
5679 * @param {Object} [config] Configuration options
5681 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5682 // Parent constructor
5683 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5685 // Mixin constructors
5686 OO
.ui
.mixin
.IconElement
.call( this, config
);
5687 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5691 .addClass( 'oo-ui-decoratedOptionWidget' )
5692 .prepend( this.$icon
)
5693 .append( this.$indicator
);
5698 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5699 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5700 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5703 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5704 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5705 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5707 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5710 * @extends OO.ui.DecoratedOptionWidget
5713 * @param {Object} [config] Configuration options
5715 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5716 // Configuration initialization
5717 config
= $.extend( { icon
: 'check' }, config
);
5719 // Parent constructor
5720 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5724 .attr( 'role', 'menuitem' )
5725 .addClass( 'oo-ui-menuOptionWidget' );
5730 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5732 /* Static Properties */
5734 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5737 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5738 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5741 * var myDropdown = new OO.ui.DropdownWidget( {
5744 * new OO.ui.MenuSectionOptionWidget( {
5747 * new OO.ui.MenuOptionWidget( {
5749 * label: 'Welsh Corgi'
5751 * new OO.ui.MenuOptionWidget( {
5753 * label: 'Standard Poodle'
5755 * new OO.ui.MenuSectionOptionWidget( {
5758 * new OO.ui.MenuOptionWidget( {
5765 * $( 'body' ).append( myDropdown.$element );
5768 * @extends OO.ui.DecoratedOptionWidget
5771 * @param {Object} [config] Configuration options
5773 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5774 // Parent constructor
5775 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5778 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5783 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5785 /* Static Properties */
5787 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5789 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5792 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5793 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5794 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5795 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5796 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5797 * and customized to be opened, closed, and displayed as needed.
5799 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5800 * mouse outside the menu.
5802 * Menus also have support for keyboard interaction:
5804 * - Enter/Return key: choose and select a menu option
5805 * - Up-arrow key: highlight the previous menu option
5806 * - Down-arrow key: highlight the next menu option
5807 * - Esc key: hide the menu
5809 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
5810 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5813 * @extends OO.ui.SelectWidget
5814 * @mixins OO.ui.mixin.ClippableElement
5817 * @param {Object} [config] Configuration options
5818 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
5819 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
5820 * and {@link OO.ui.mixin.LookupElement LookupElement}
5821 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
5822 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
5823 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
5824 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
5825 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
5826 * that button, unless the button (or its parent widget) is passed in here.
5827 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
5828 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
5830 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
5831 // Configuration initialization
5832 config
= config
|| {};
5834 // Parent constructor
5835 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
5837 // Mixin constructors
5838 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
5841 this.newItems
= null;
5842 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
5843 this.filterFromInput
= !!config
.filterFromInput
;
5844 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
5845 this.$widget
= config
.widget
? config
.widget
.$element
: null;
5846 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
5847 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
5851 .addClass( 'oo-ui-menuSelectWidget' )
5852 .attr( 'role', 'menu' );
5854 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5855 // that reference properties not initialized at that time of parent class construction
5856 // TODO: Find a better way to handle post-constructor setup
5857 this.visible
= false;
5858 this.$element
.addClass( 'oo-ui-element-hidden' );
5863 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
5864 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
5869 * Handles document mouse down events.
5872 * @param {MouseEvent} e Mouse down event
5874 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
5876 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
5877 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
5879 this.toggle( false );
5886 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
5887 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5889 if ( !this.isDisabled() && this.isVisible() ) {
5890 switch ( e
.keyCode
) {
5891 case OO
.ui
.Keys
.LEFT
:
5892 case OO
.ui
.Keys
.RIGHT
:
5893 // Do nothing if a text field is associated, arrow keys will be handled natively
5894 if ( !this.$input
) {
5895 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
5898 case OO
.ui
.Keys
.ESCAPE
:
5899 case OO
.ui
.Keys
.TAB
:
5900 if ( currentItem
) {
5901 currentItem
.setHighlighted( false );
5903 this.toggle( false );
5904 // Don't prevent tabbing away, prevent defocusing
5905 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
5907 e
.stopPropagation();
5911 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
5918 * Update menu item visibility after input changes.
5921 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
5923 len
= this.items
.length
,
5924 showAll
= !this.isVisible(),
5925 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
5927 for ( i
= 0; i
< len
; i
++ ) {
5928 item
= this.items
[ i
];
5929 if ( item
instanceof OO
.ui
.OptionWidget
) {
5930 item
.toggle( showAll
|| filter( item
) );
5934 // Reevaluate clipping
5941 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
5942 if ( this.$input
) {
5943 this.$input
.on( 'keydown', this.onKeyDownHandler
);
5945 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
5952 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
5953 if ( this.$input
) {
5954 this.$input
.off( 'keydown', this.onKeyDownHandler
);
5956 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
5963 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
5964 if ( this.$input
) {
5965 if ( this.filterFromInput
) {
5966 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
5969 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
5976 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
5977 if ( this.$input
) {
5978 if ( this.filterFromInput
) {
5979 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
5980 this.updateItemVisibility();
5983 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
5990 * When a user chooses an item, the menu is closed.
5992 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
5993 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
5994 * @param {OO.ui.OptionWidget} item Item to choose
5997 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
5998 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
5999 this.toggle( false );
6006 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6010 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6013 if ( !this.newItems
) {
6017 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6019 if ( this.isVisible() ) {
6020 // Defer fitting label until item has been attached
6023 this.newItems
.push( item
);
6027 // Reevaluate clipping
6036 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6038 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6040 // Reevaluate clipping
6049 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6051 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6053 // Reevaluate clipping
6062 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6065 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6066 change
= visible
!== this.isVisible();
6069 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6073 this.bindKeyDownListener();
6074 this.bindKeyPressListener();
6076 if ( this.newItems
&& this.newItems
.length
) {
6077 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
6078 this.newItems
[ i
].fitLabel();
6080 this.newItems
= null;
6082 this.toggleClipping( true );
6084 if ( this.getSelectedItem() ) {
6085 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6089 if ( this.autoHide
) {
6090 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6093 this.unbindKeyDownListener();
6094 this.unbindKeyPressListener();
6095 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6096 this.toggleClipping( false );
6104 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6105 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6106 * users can interact with it.
6108 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6109 * OO.ui.DropdownInputWidget instead.
6112 * // Example: A DropdownWidget with a menu that contains three options
6113 * var dropDown = new OO.ui.DropdownWidget( {
6114 * label: 'Dropdown menu: Select a menu option',
6117 * new OO.ui.MenuOptionWidget( {
6121 * new OO.ui.MenuOptionWidget( {
6125 * new OO.ui.MenuOptionWidget( {
6133 * $( 'body' ).append( dropDown.$element );
6135 * dropDown.getMenu().selectItemByData( 'b' );
6137 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6139 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6141 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6144 * @extends OO.ui.Widget
6145 * @mixins OO.ui.mixin.IconElement
6146 * @mixins OO.ui.mixin.IndicatorElement
6147 * @mixins OO.ui.mixin.LabelElement
6148 * @mixins OO.ui.mixin.TitledElement
6149 * @mixins OO.ui.mixin.TabIndexedElement
6152 * @param {Object} [config] Configuration options
6153 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6154 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6155 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6156 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6158 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6159 // Configuration initialization
6160 config
= $.extend( { indicator
: 'down' }, config
);
6162 // Parent constructor
6163 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6165 // Properties (must be set before TabIndexedElement constructor call)
6166 this.$handle
= this.$( '<span>' );
6167 this.$overlay
= config
.$overlay
|| this.$element
;
6169 // Mixin constructors
6170 OO
.ui
.mixin
.IconElement
.call( this, config
);
6171 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6172 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6173 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6174 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6177 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6179 $container
: this.$element
6184 click
: this.onClick
.bind( this ),
6185 keydown
: this.onKeyDown
.bind( this )
6187 this.menu
.connect( this, { select
: 'onMenuSelect' } );
6191 .addClass( 'oo-ui-dropdownWidget-handle' )
6192 .append( this.$icon
, this.$label
, this.$indicator
);
6194 .addClass( 'oo-ui-dropdownWidget' )
6195 .append( this.$handle
);
6196 this.$overlay
.append( this.menu
.$element
);
6201 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6202 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6203 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6204 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6205 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6206 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6213 * @return {OO.ui.MenuSelectWidget} Menu of widget
6215 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6220 * Handles menu select events.
6223 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6225 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6229 this.setLabel( null );
6233 selectedLabel
= item
.getLabel();
6235 // If the label is a DOM element, clone it, because setLabel will append() it
6236 if ( selectedLabel
instanceof jQuery
) {
6237 selectedLabel
= selectedLabel
.clone();
6240 this.setLabel( selectedLabel
);
6244 * Handle mouse click events.
6247 * @param {jQuery.Event} e Mouse click event
6249 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6250 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6257 * Handle key down events.
6260 * @param {jQuery.Event} e Key down event
6262 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6264 !this.isDisabled() &&
6266 e
.which
=== OO
.ui
.Keys
.ENTER
||
6268 !this.menu
.isVisible() &&
6270 e
.which
=== OO
.ui
.Keys
.SPACE
||
6271 e
.which
=== OO
.ui
.Keys
.UP
||
6272 e
.which
=== OO
.ui
.Keys
.DOWN
6283 * RadioOptionWidget is an option widget that looks like a radio button.
6284 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6285 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6287 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6290 * @extends OO.ui.OptionWidget
6293 * @param {Object} [config] Configuration options
6295 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6296 // Configuration initialization
6297 config
= config
|| {};
6299 // Properties (must be done before parent constructor which calls #setDisabled)
6300 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6302 // Parent constructor
6303 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6306 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
6309 // Remove implicit role, we're handling it ourselves
6310 this.radio
.$input
.attr( 'role', 'presentation' );
6312 .addClass( 'oo-ui-radioOptionWidget' )
6313 .attr( 'role', 'radio' )
6314 .attr( 'aria-checked', 'false' )
6315 .removeAttr( 'aria-selected' )
6316 .prepend( this.radio
.$element
);
6321 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6323 /* Static Properties */
6325 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6327 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6329 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6331 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6336 * @param {jQuery.Event} e Focus event
6339 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
6340 this.radio
.$input
.blur();
6341 this.$element
.parent().focus();
6347 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6348 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6350 this.radio
.setSelected( state
);
6352 .attr( 'aria-checked', state
.toString() )
6353 .removeAttr( 'aria-selected' );
6361 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6362 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6364 this.radio
.setDisabled( this.isDisabled() );
6370 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6371 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6372 * an interface for adding, removing and selecting options.
6373 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6375 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6376 * OO.ui.RadioSelectInputWidget instead.
6379 * // A RadioSelectWidget with RadioOptions.
6380 * var option1 = new OO.ui.RadioOptionWidget( {
6382 * label: 'Selected radio option'
6385 * var option2 = new OO.ui.RadioOptionWidget( {
6387 * label: 'Unselected radio option'
6390 * var radioSelect=new OO.ui.RadioSelectWidget( {
6391 * items: [ option1, option2 ]
6394 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6395 * radioSelect.selectItem( option1 );
6397 * $( 'body' ).append( radioSelect.$element );
6399 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6403 * @extends OO.ui.SelectWidget
6404 * @mixins OO.ui.mixin.TabIndexedElement
6407 * @param {Object} [config] Configuration options
6409 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6410 // Parent constructor
6411 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6413 // Mixin constructors
6414 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6418 focus
: this.bindKeyDownListener
.bind( this ),
6419 blur
: this.unbindKeyDownListener
.bind( this )
6424 .addClass( 'oo-ui-radioSelectWidget' )
6425 .attr( 'role', 'radiogroup' );
6430 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6431 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6434 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6435 * document (for example, in a OO.ui.Window's $overlay).
6437 * The elements's position is automatically calculated and maintained when window is resized or the
6438 * page is scrolled. If you reposition the container manually, you have to call #position to make
6439 * sure the element is still placed correctly.
6441 * As positioning is only possible when both the element and the container are attached to the DOM
6442 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6443 * the #toggle method to display a floating popup, for example.
6449 * @param {Object} [config] Configuration options
6450 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6451 * @cfg {jQuery} [$floatableContainer] Node to position below
6453 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6454 // Configuration initialization
6455 config
= config
|| {};
6458 this.$floatable
= null;
6459 this.$floatableContainer
= null;
6460 this.$floatableWindow
= null;
6461 this.$floatableClosestScrollable
= null;
6462 this.onFloatableScrollHandler
= this.position
.bind( this );
6463 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6466 this.setFloatableContainer( config
.$floatableContainer
);
6467 this.setFloatableElement( config
.$floatable
|| this.$element
);
6473 * Set floatable element.
6475 * If an element is already set, it will be cleaned up before setting up the new element.
6477 * @param {jQuery} $floatable Element to make floatable
6479 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6480 if ( this.$floatable
) {
6481 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6482 this.$floatable
.css( { left
: '', top
: '' } );
6485 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6490 * Set floatable container.
6492 * The element will be always positioned under the specified container.
6494 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6496 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6497 this.$floatableContainer
= $floatableContainer
;
6498 if ( this.$floatable
) {
6504 * Toggle positioning.
6506 * Do not turn positioning on until after the element is attached to the DOM and visible.
6508 * @param {boolean} [positioning] Enable positioning, omit to toggle
6511 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6512 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6514 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6516 if ( this.positioning
!== positioning
) {
6517 this.positioning
= positioning
;
6519 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6520 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6521 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6522 // If the scrollable is the root, we have to listen to scroll events
6523 // on the window because of browser inconsistencies (or do we? someone should verify this)
6524 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6525 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6529 if ( positioning
) {
6530 this.$floatableWindow
= $( this.getElementWindow() );
6531 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6533 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6534 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6535 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6538 // Initial position after visible
6541 if ( this.$floatableWindow
) {
6542 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6543 this.$floatableWindow
= null;
6546 if ( this.$floatableClosestScrollable
) {
6547 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6548 this.$floatableClosestScrollable
= null;
6551 this.$floatable
.css( { left
: '', top
: '' } );
6559 * Position the floatable below its container.
6561 * This should only be done when both of them are attached to the DOM and visible.
6565 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6568 if ( !this.positioning
) {
6572 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6574 // Position under container
6575 pos
.top
+= this.$floatableContainer
.height();
6576 this.$floatable
.css( pos
);
6578 // We updated the position, so re-evaluate the clipping state.
6579 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6580 // will not notice the need to update itself.)
6581 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6582 // it not listen to the right events in the right places?
6591 * FloatingMenuSelectWidget is a menu that will stick under a specified
6592 * container, even when it is inserted elsewhere in the document (for example,
6593 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
6594 * menu from being clipped too aggresively.
6596 * The menu's position is automatically calculated and maintained when the menu
6597 * is toggled or the window is resized.
6599 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
6602 * @extends OO.ui.MenuSelectWidget
6603 * @mixins OO.ui.mixin.FloatableElement
6606 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
6607 * Deprecated, omit this parameter and specify `$container` instead.
6608 * @param {Object} [config] Configuration options
6609 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
6611 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
6612 // Allow 'inputWidget' parameter and config for backwards compatibility
6613 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
6614 config
= inputWidget
;
6615 inputWidget
= config
.inputWidget
;
6618 // Configuration initialization
6619 config
= config
|| {};
6621 // Parent constructor
6622 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
6624 // Properties (must be set before mixin constructors)
6625 this.inputWidget
= inputWidget
; // For backwards compatibility
6626 this.$container
= config
.$container
|| this.inputWidget
.$element
;
6628 // Mixins constructors
6629 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
6632 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
6633 // For backwards compatibility
6634 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
6639 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
6640 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6642 // For backwards compatibility
6643 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
6650 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
6652 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
6653 change
= visible
!== this.isVisible();
6655 if ( change
&& visible
) {
6656 // Make sure the width is set before the parent method runs.
6657 this.setIdealSize( this.$container
.width() );
6661 // This will call this.clip(), which is nonsensical since we're not positioned yet...
6662 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6665 this.togglePositioning( this.isVisible() );
6672 * InputWidget is the base class for all input widgets, which
6673 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
6674 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
6675 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6677 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
6681 * @extends OO.ui.Widget
6682 * @mixins OO.ui.mixin.FlaggedElement
6683 * @mixins OO.ui.mixin.TabIndexedElement
6684 * @mixins OO.ui.mixin.TitledElement
6685 * @mixins OO.ui.mixin.AccessKeyedElement
6688 * @param {Object} [config] Configuration options
6689 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
6690 * @cfg {string} [value=''] The value of the input.
6691 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
6692 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
6693 * before it is accepted.
6695 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
6696 // Configuration initialization
6697 config
= config
|| {};
6699 // Parent constructor
6700 OO
.ui
.InputWidget
.parent
.call( this, config
);
6703 this.$input
= this.getInputElement( config
);
6705 this.inputFilter
= config
.inputFilter
;
6707 // Mixin constructors
6708 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6709 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
6710 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
6711 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
6714 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
6718 .addClass( 'oo-ui-inputWidget-input' )
6719 .attr( 'name', config
.name
)
6720 .prop( 'disabled', this.isDisabled() );
6722 .addClass( 'oo-ui-inputWidget' )
6723 .append( this.$input
);
6724 this.setValue( config
.value
);
6726 this.setDir( config
.dir
);
6732 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
6733 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
6734 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6735 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
6736 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6738 /* Static Properties */
6740 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
6742 /* Static Methods */
6747 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
6748 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
6749 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
6750 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
6757 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
6758 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
6759 state
.value
= config
.$input
.val();
6760 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
6761 state
.focus
= config
.$input
.is( ':focus' );
6770 * A change event is emitted when the value of the input changes.
6772 * @param {string} value
6778 * Get input element.
6780 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
6781 * different circumstances. The element must have a `value` property (like form elements).
6784 * @param {Object} config Configuration options
6785 * @return {jQuery} Input element
6787 OO
.ui
.InputWidget
.prototype.getInputElement = function ( config
) {
6788 // See #reusePreInfuseDOM about config.$input
6789 return config
.$input
|| $( '<input>' );
6793 * Handle potentially value-changing events.
6796 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
6798 OO
.ui
.InputWidget
.prototype.onEdit = function () {
6800 if ( !this.isDisabled() ) {
6801 // Allow the stack to clear so the value will be updated
6802 setTimeout( function () {
6803 widget
.setValue( widget
.$input
.val() );
6809 * Get the value of the input.
6811 * @return {string} Input value
6813 OO
.ui
.InputWidget
.prototype.getValue = function () {
6814 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
6815 // it, and we won't know unless they're kind enough to trigger a 'change' event.
6816 var value
= this.$input
.val();
6817 if ( this.value
!== value
) {
6818 this.setValue( value
);
6824 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
6826 * @deprecated since v0.13.1, use #setDir directly
6827 * @param {boolean} isRTL Directionality is right-to-left
6830 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
6831 this.setDir( isRTL
? 'rtl' : 'ltr' );
6836 * Set the directionality of the input.
6838 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
6841 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
6842 this.$input
.prop( 'dir', dir
);
6847 * Set the value of the input.
6849 * @param {string} value New value
6853 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
6854 value
= this.cleanUpValue( value
);
6855 // Update the DOM if it has changed. Note that with cleanUpValue, it
6856 // is possible for the DOM value to change without this.value changing.
6857 if ( this.$input
.val() !== value
) {
6858 this.$input
.val( value
);
6860 if ( this.value
!== value
) {
6862 this.emit( 'change', this.value
);
6868 * Clean up incoming value.
6870 * Ensures value is a string, and converts undefined and null to empty string.
6873 * @param {string} value Original value
6874 * @return {string} Cleaned up value
6876 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
6877 if ( value
=== undefined || value
=== null ) {
6879 } else if ( this.inputFilter
) {
6880 return this.inputFilter( String( value
) );
6882 return String( value
);
6887 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
6888 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
6891 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
6892 if ( !this.isDisabled() ) {
6893 if ( this.$input
.is( ':checkbox, :radio' ) ) {
6894 this.$input
.click();
6896 if ( this.$input
.is( ':input' ) ) {
6897 this.$input
[ 0 ].focus();
6905 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
6906 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
6907 if ( this.$input
) {
6908 this.$input
.prop( 'disabled', this.isDisabled() );
6918 OO
.ui
.InputWidget
.prototype.focus = function () {
6919 this.$input
[ 0 ].focus();
6928 OO
.ui
.InputWidget
.prototype.blur = function () {
6929 this.$input
[ 0 ].blur();
6936 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
6937 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
6938 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
6939 this.setValue( state
.value
);
6941 if ( state
.focus
) {
6947 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
6948 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
6949 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
6950 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
6951 * [OOjs UI documentation on MediaWiki] [1] for more information.
6954 * // A ButtonInputWidget rendered as an HTML button, the default.
6955 * var button = new OO.ui.ButtonInputWidget( {
6956 * label: 'Input button',
6960 * $( 'body' ).append( button.$element );
6962 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
6965 * @extends OO.ui.InputWidget
6966 * @mixins OO.ui.mixin.ButtonElement
6967 * @mixins OO.ui.mixin.IconElement
6968 * @mixins OO.ui.mixin.IndicatorElement
6969 * @mixins OO.ui.mixin.LabelElement
6970 * @mixins OO.ui.mixin.TitledElement
6973 * @param {Object} [config] Configuration options
6974 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
6975 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
6976 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
6977 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
6978 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
6980 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
6981 // Configuration initialization
6982 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
6984 // Properties (must be set before parent constructor, which calls #setValue)
6985 this.useInputTag
= config
.useInputTag
;
6987 // Parent constructor
6988 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
6990 // Mixin constructors
6991 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
6992 OO
.ui
.mixin
.IconElement
.call( this, config
);
6993 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6994 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6995 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
6998 if ( !config
.useInputTag
) {
6999 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7001 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7006 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7007 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7008 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7009 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7010 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7011 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7013 /* Static Properties */
7016 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7017 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7019 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7027 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7029 // See InputWidget#reusePreInfuseDOM about config.$input
7030 if ( config
.$input
) {
7031 return config
.$input
.empty();
7033 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7034 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7040 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
7042 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7043 * text, or `null` for no label
7046 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7047 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7049 if ( this.useInputTag
) {
7050 if ( typeof label
=== 'function' ) {
7051 label
= OO
.ui
.resolveMsg( label
);
7053 if ( label
instanceof jQuery
) {
7054 label
= label
.text();
7059 this.$input
.val( label
);
7066 * Set the value of the input.
7068 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
7069 * they do not support {@link #value values}.
7071 * @param {string} value New value
7074 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7075 if ( !this.useInputTag
) {
7076 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7082 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7083 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7084 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7085 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7087 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7090 * // An example of selected, unselected, and disabled checkbox inputs
7091 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7095 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7098 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7102 * // Create a fieldset layout with fields for each checkbox.
7103 * var fieldset = new OO.ui.FieldsetLayout( {
7104 * label: 'Checkboxes'
7106 * fieldset.addItems( [
7107 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7108 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7109 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7111 * $( 'body' ).append( fieldset.$element );
7113 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7116 * @extends OO.ui.InputWidget
7119 * @param {Object} [config] Configuration options
7120 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7122 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7123 // Configuration initialization
7124 config
= config
|| {};
7126 // Parent constructor
7127 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7131 .addClass( 'oo-ui-checkboxInputWidget' )
7132 // Required for pretty styling in MediaWiki theme
7133 .append( $( '<span>' ) );
7134 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7139 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7141 /* Static Methods */
7146 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7147 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7148 state
.checked
= config
.$input
.prop( 'checked' );
7158 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7159 return $( '<input type="checkbox" />' );
7165 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7167 if ( !this.isDisabled() ) {
7168 // Allow the stack to clear so the value will be updated
7169 setTimeout( function () {
7170 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7176 * Set selection state of this checkbox.
7178 * @param {boolean} state `true` for selected
7181 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7183 if ( this.selected
!== state
) {
7184 this.selected
= state
;
7185 this.$input
.prop( 'checked', this.selected
);
7186 this.emit( 'change', this.selected
);
7192 * Check if this checkbox is selected.
7194 * @return {boolean} Checkbox is selected
7196 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7197 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7198 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7199 var selected
= this.$input
.prop( 'checked' );
7200 if ( this.selected
!== selected
) {
7201 this.setSelected( selected
);
7203 return this.selected
;
7209 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7210 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7211 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7212 this.setSelected( state
.checked
);
7217 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7218 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7219 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7220 * more information about input widgets.
7222 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7223 * are no options. If no `value` configuration option is provided, the first option is selected.
7224 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7226 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7229 * // Example: A DropdownInputWidget with three options
7230 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7232 * { data: 'a', label: 'First' },
7233 * { data: 'b', label: 'Second'},
7234 * { data: 'c', label: 'Third' }
7237 * $( 'body' ).append( dropdownInput.$element );
7239 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7242 * @extends OO.ui.InputWidget
7243 * @mixins OO.ui.mixin.TitledElement
7246 * @param {Object} [config] Configuration options
7247 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7248 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
7250 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
7251 // Configuration initialization
7252 config
= config
|| {};
7254 // Properties (must be done before parent constructor which calls #setDisabled)
7255 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
7257 // Parent constructor
7258 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
7260 // Mixin constructors
7261 OO
.ui
.mixin
.TitledElement
.call( this, config
);
7264 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
7267 this.setOptions( config
.options
|| [] );
7269 .addClass( 'oo-ui-dropdownInputWidget' )
7270 .append( this.dropdownWidget
.$element
);
7275 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
7276 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
7284 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function ( config
) {
7285 // See InputWidget#reusePreInfuseDOM about config.$input
7286 if ( config
.$input
) {
7287 return config
.$input
.addClass( 'oo-ui-element-hidden' );
7289 return $( '<input type="hidden">' );
7293 * Handles menu select events.
7296 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7298 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
7299 this.setValue( item
.getData() );
7305 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
7306 value
= this.cleanUpValue( value
);
7307 this.dropdownWidget
.getMenu().selectItemByData( value
);
7308 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
7315 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
7316 this.dropdownWidget
.setDisabled( state
);
7317 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7322 * Set the options available for this input.
7324 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7327 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
7329 value
= this.getValue(),
7332 // Rebuild the dropdown menu
7333 this.dropdownWidget
.getMenu()
7335 .addItems( options
.map( function ( opt
) {
7336 var optValue
= widget
.cleanUpValue( opt
.data
);
7337 return new OO
.ui
.MenuOptionWidget( {
7339 label
: opt
.label
!== undefined ? opt
.label
: optValue
7343 // Restore the previous value, or reset to something sensible
7344 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
7345 // Previous value is still available, ensure consistency with the dropdown
7346 this.setValue( value
);
7348 // No longer valid, reset
7349 if ( options
.length
) {
7350 this.setValue( options
[ 0 ].data
);
7360 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
7361 this.dropdownWidget
.getMenu().toggle( true );
7368 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
7369 this.dropdownWidget
.getMenu().toggle( false );
7374 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
7375 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
7376 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
7377 * please see the [OOjs UI documentation on MediaWiki][1].
7379 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7382 * // An example of selected, unselected, and disabled radio inputs
7383 * var radio1 = new OO.ui.RadioInputWidget( {
7387 * var radio2 = new OO.ui.RadioInputWidget( {
7390 * var radio3 = new OO.ui.RadioInputWidget( {
7394 * // Create a fieldset layout with fields for each radio button.
7395 * var fieldset = new OO.ui.FieldsetLayout( {
7396 * label: 'Radio inputs'
7398 * fieldset.addItems( [
7399 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
7400 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
7401 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
7403 * $( 'body' ).append( fieldset.$element );
7405 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7408 * @extends OO.ui.InputWidget
7411 * @param {Object} [config] Configuration options
7412 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
7414 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
7415 // Configuration initialization
7416 config
= config
|| {};
7418 // Parent constructor
7419 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
7423 .addClass( 'oo-ui-radioInputWidget' )
7424 // Required for pretty styling in MediaWiki theme
7425 .append( $( '<span>' ) );
7426 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7431 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
7433 /* Static Methods */
7438 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7439 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7440 state
.checked
= config
.$input
.prop( 'checked' );
7450 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
7451 return $( '<input type="radio" />' );
7457 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
7458 // RadioInputWidget doesn't track its state.
7462 * Set selection state of this radio button.
7464 * @param {boolean} state `true` for selected
7467 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
7468 // RadioInputWidget doesn't track its state.
7469 this.$input
.prop( 'checked', state
);
7474 * Check if this radio button is selected.
7476 * @return {boolean} Radio is selected
7478 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
7479 return this.$input
.prop( 'checked' );
7485 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7486 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7487 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7488 this.setSelected( state
.checked
);
7493 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
7494 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7495 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7496 * more information about input widgets.
7498 * This and OO.ui.DropdownInputWidget support the same configuration options.
7501 * // Example: A RadioSelectInputWidget with three options
7502 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
7504 * { data: 'a', label: 'First' },
7505 * { data: 'b', label: 'Second'},
7506 * { data: 'c', label: 'Third' }
7509 * $( 'body' ).append( radioSelectInput.$element );
7511 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7514 * @extends OO.ui.InputWidget
7517 * @param {Object} [config] Configuration options
7518 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
7520 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
7521 // Configuration initialization
7522 config
= config
|| {};
7524 // Properties (must be done before parent constructor which calls #setDisabled)
7525 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
7527 // Parent constructor
7528 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
7531 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
7534 this.setOptions( config
.options
|| [] );
7536 .addClass( 'oo-ui-radioSelectInputWidget' )
7537 .append( this.radioSelectWidget
.$element
);
7542 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
7544 /* Static Properties */
7546 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
7548 /* Static Methods */
7553 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7554 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7555 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
7565 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
7566 return $( '<input type="hidden">' );
7570 * Handles menu select events.
7573 * @param {OO.ui.RadioOptionWidget} item Selected menu item
7575 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
7576 this.setValue( item
.getData() );
7582 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
7583 value
= this.cleanUpValue( value
);
7584 this.radioSelectWidget
.selectItemByData( value
);
7585 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
7592 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
7593 this.radioSelectWidget
.setDisabled( state
);
7594 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7599 * Set the options available for this input.
7601 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
7604 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
7606 value
= this.getValue(),
7609 // Rebuild the radioSelect menu
7610 this.radioSelectWidget
7612 .addItems( options
.map( function ( opt
) {
7613 var optValue
= widget
.cleanUpValue( opt
.data
);
7614 return new OO
.ui
.RadioOptionWidget( {
7616 label
: opt
.label
!== undefined ? opt
.label
: optValue
7620 // Restore the previous value, or reset to something sensible
7621 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
7622 // Previous value is still available, ensure consistency with the radioSelect
7623 this.setValue( value
);
7625 // No longer valid, reset
7626 if ( options
.length
) {
7627 this.setValue( options
[ 0 ].data
);
7635 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
7636 * size of the field as well as its presentation. In addition, these widgets can be configured
7637 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
7638 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
7639 * which modifies incoming values rather than validating them.
7640 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7642 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7645 * // Example of a text input widget
7646 * var textInput = new OO.ui.TextInputWidget( {
7647 * value: 'Text input'
7649 * $( 'body' ).append( textInput.$element );
7651 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7654 * @extends OO.ui.InputWidget
7655 * @mixins OO.ui.mixin.IconElement
7656 * @mixins OO.ui.mixin.IndicatorElement
7657 * @mixins OO.ui.mixin.PendingElement
7658 * @mixins OO.ui.mixin.LabelElement
7661 * @param {Object} [config] Configuration options
7662 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
7663 * 'email' or 'url'. Ignored if `multiline` is true.
7665 * Some values of `type` result in additional behaviors:
7667 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
7668 * empties the text field
7669 * @cfg {string} [placeholder] Placeholder text
7670 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
7671 * instruct the browser to focus this widget.
7672 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
7673 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
7674 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7675 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
7676 * specifies minimum number of rows to display.
7677 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
7678 * Use the #maxRows config to specify a maximum number of displayed rows.
7679 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
7680 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
7681 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
7682 * the value or placeholder text: `'before'` or `'after'`
7683 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
7684 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
7685 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
7686 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
7687 * (the value must contain only numbers); when RegExp, a regular expression that must match the
7688 * value for it to be considered valid; when Function, a function receiving the value as parameter
7689 * that must return true, or promise resolving to true, for it to be considered valid.
7691 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
7692 // Configuration initialization
7693 config
= $.extend( {
7695 labelPosition
: 'after'
7697 if ( config
.type
=== 'search' ) {
7698 if ( config
.icon
=== undefined ) {
7699 config
.icon
= 'search';
7701 // indicator: 'clear' is set dynamically later, depending on value
7703 if ( config
.required
) {
7704 if ( config
.indicator
=== undefined ) {
7705 config
.indicator
= 'required';
7709 // Parent constructor
7710 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
7712 // Mixin constructors
7713 OO
.ui
.mixin
.IconElement
.call( this, config
);
7714 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7715 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
7716 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7719 this.type
= this.getSaneType( config
);
7720 this.readOnly
= false;
7721 this.multiline
= !!config
.multiline
;
7722 this.autosize
= !!config
.autosize
;
7723 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
7724 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
7725 this.validate
= null;
7726 this.styleHeight
= null;
7727 this.scrollWidth
= null;
7729 // Clone for resizing
7730 if ( this.autosize
) {
7731 this.$clone
= this.$input
7733 .insertAfter( this.$input
)
7734 .attr( 'aria-hidden', 'true' )
7735 .addClass( 'oo-ui-element-hidden' );
7738 this.setValidation( config
.validate
);
7739 this.setLabelPosition( config
.labelPosition
);
7743 keypress
: this.onKeyPress
.bind( this ),
7744 blur
: this.onBlur
.bind( this )
7747 focus
: this.onElementAttach
.bind( this )
7749 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
7750 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
7751 this.on( 'labelChange', this.updatePosition
.bind( this ) );
7752 this.connect( this, {
7754 disable
: 'onDisable'
7759 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
7760 .append( this.$icon
, this.$indicator
);
7761 this.setReadOnly( !!config
.readOnly
);
7762 this.updateSearchIndicator();
7763 if ( config
.placeholder
) {
7764 this.$input
.attr( 'placeholder', config
.placeholder
);
7766 if ( config
.maxLength
!== undefined ) {
7767 this.$input
.attr( 'maxlength', config
.maxLength
);
7769 if ( config
.autofocus
) {
7770 this.$input
.attr( 'autofocus', 'autofocus' );
7772 if ( config
.required
) {
7773 this.$input
.attr( 'required', 'required' );
7774 this.$input
.attr( 'aria-required', 'true' );
7776 if ( config
.autocomplete
=== false ) {
7777 this.$input
.attr( 'autocomplete', 'off' );
7778 // Turning off autocompletion also disables "form caching" when the user navigates to a
7779 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
7781 beforeunload: function () {
7782 this.$input
.removeAttr( 'autocomplete' );
7784 pageshow: function () {
7785 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
7786 // whole page... it shouldn't hurt, though.
7787 this.$input
.attr( 'autocomplete', 'off' );
7791 if ( this.multiline
&& config
.rows
) {
7792 this.$input
.attr( 'rows', config
.rows
);
7794 if ( this.label
|| config
.autosize
) {
7795 this.installParentChangeDetector();
7801 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
7802 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
7803 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7804 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
7805 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
7807 /* Static Properties */
7809 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
7814 /* Static Methods */
7819 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7820 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7821 if ( config
.multiline
) {
7822 state
.scrollTop
= config
.$input
.scrollTop();
7830 * An `enter` event is emitted when the user presses 'enter' inside the text box.
7832 * Not emitted if the input is multiline.
7838 * A `resize` event is emitted when autosize is set and the widget resizes
7846 * Handle icon mouse down events.
7849 * @param {jQuery.Event} e Mouse down event
7852 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
7853 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7854 this.$input
[ 0 ].focus();
7860 * Handle indicator mouse down events.
7863 * @param {jQuery.Event} e Mouse down event
7866 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
7867 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7868 if ( this.type
=== 'search' ) {
7869 // Clear the text field
7870 this.setValue( '' );
7872 this.$input
[ 0 ].focus();
7878 * Handle key press events.
7881 * @param {jQuery.Event} e Key press event
7882 * @fires enter If enter key is pressed and input is not multiline
7884 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
7885 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
7886 this.emit( 'enter', e
);
7891 * Handle blur events.
7894 * @param {jQuery.Event} e Blur event
7896 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
7897 this.setValidityFlag();
7901 * Handle element attach events.
7904 * @param {jQuery.Event} e Element attach event
7906 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
7907 // Any previously calculated size is now probably invalid if we reattached elsewhere
7908 this.valCache
= null;
7910 this.positionLabel();
7914 * Handle change events.
7916 * @param {string} value
7919 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
7920 this.updateSearchIndicator();
7921 this.setValidityFlag();
7926 * Handle disable events.
7928 * @param {boolean} disabled Element is disabled
7931 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
7932 this.updateSearchIndicator();
7936 * Check if the input is {@link #readOnly read-only}.
7940 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
7941 return this.readOnly
;
7945 * Set the {@link #readOnly read-only} state of the input.
7947 * @param {boolean} state Make input read-only
7950 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
7951 this.readOnly
= !!state
;
7952 this.$input
.prop( 'readOnly', this.readOnly
);
7953 this.updateSearchIndicator();
7958 * Support function for making #onElementAttach work across browsers.
7960 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
7961 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
7963 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
7964 * first time that the element gets attached to the documented.
7966 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
7967 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
7968 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
7971 if ( MutationObserver
) {
7972 // The new way. If only it wasn't so ugly.
7974 if ( this.$element
.closest( 'html' ).length
) {
7975 // Widget is attached already, do nothing. This breaks the functionality of this function when
7976 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
7977 // would require observation of the whole document, which would hurt performance of other,
7978 // more important code.
7982 // Find topmost node in the tree
7983 topmostNode
= this.$element
[ 0 ];
7984 while ( topmostNode
.parentNode
) {
7985 topmostNode
= topmostNode
.parentNode
;
7988 // We have no way to detect the $element being attached somewhere without observing the entire
7989 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
7990 // parent node of $element, and instead detect when $element is removed from it (and thus
7991 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
7992 // doesn't get attached, we end up back here and create the parent.
7994 mutationObserver
= new MutationObserver( function ( mutations
) {
7995 var i
, j
, removedNodes
;
7996 for ( i
= 0; i
< mutations
.length
; i
++ ) {
7997 removedNodes
= mutations
[ i
].removedNodes
;
7998 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
7999 if ( removedNodes
[ j
] === topmostNode
) {
8000 setTimeout( onRemove
, 0 );
8007 onRemove = function () {
8008 // If the node was attached somewhere else, report it
8009 if ( widget
.$element
.closest( 'html' ).length
) {
8010 widget
.onElementAttach();
8012 mutationObserver
.disconnect();
8013 widget
.installParentChangeDetector();
8016 // Create a fake parent and observe it
8017 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8018 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8020 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8021 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8022 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8027 * Automatically adjust the size of the text input.
8029 * This only affects #multiline inputs that are {@link #autosize autosized}.
8034 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
8035 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
8036 idealHeight
, newHeight
, scrollWidth
, property
;
8038 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
8039 if ( this.autosize
) {
8041 .val( this.$input
.val() )
8042 .attr( 'rows', this.minRows
)
8043 // Set inline height property to 0 to measure scroll height
8044 .css( 'height', 0 );
8046 this.$clone
.removeClass( 'oo-ui-element-hidden' );
8048 this.valCache
= this.$input
.val();
8050 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
8052 // Remove inline height property to measure natural heights
8053 this.$clone
.css( 'height', '' );
8054 innerHeight
= this.$clone
.innerHeight();
8055 outerHeight
= this.$clone
.outerHeight();
8057 // Measure max rows height
8059 .attr( 'rows', this.maxRows
)
8060 .css( 'height', 'auto' )
8062 maxInnerHeight
= this.$clone
.innerHeight();
8064 // Difference between reported innerHeight and scrollHeight with no scrollbars present
8065 // Equals 1 on Blink-based browsers and 0 everywhere else
8066 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
8067 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
8069 this.$clone
.addClass( 'oo-ui-element-hidden' );
8071 // Only apply inline height when expansion beyond natural height is needed
8072 // Use the difference between the inner and outer height as a buffer
8073 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
8074 if ( newHeight
!== this.styleHeight
) {
8075 this.$input
.css( 'height', newHeight
);
8076 this.styleHeight
= newHeight
;
8077 this.emit( 'resize' );
8080 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
8081 if ( scrollWidth
!== this.scrollWidth
) {
8082 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
8084 this.$label
.css( { right
: '', left
: '' } );
8085 this.$indicator
.css( { right
: '', left
: '' } );
8087 if ( scrollWidth
) {
8088 this.$indicator
.css( property
, scrollWidth
);
8089 if ( this.labelPosition
=== 'after' ) {
8090 this.$label
.css( property
, scrollWidth
);
8094 this.scrollWidth
= scrollWidth
;
8095 this.positionLabel();
8105 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
8106 return config
.multiline
?
8108 $( '<input type="' + this.getSaneType( config
) + '" />' );
8112 * Get sanitized value for 'type' for given config.
8114 * @param {Object} config Configuration options
8115 * @return {string|null}
8118 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
8119 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
8122 return config
.multiline
? 'multiline' : type
;
8126 * Check if the input supports multiple lines.
8130 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
8131 return !!this.multiline
;
8135 * Check if the input automatically adjusts its size.
8139 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
8140 return !!this.autosize
;
8144 * Focus the input and select a specified range within the text.
8146 * @param {number} from Select from offset
8147 * @param {number} [to] Select to offset, defaults to from
8150 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
8151 var isBackwards
, start
, end
,
8152 input
= this.$input
[ 0 ];
8156 isBackwards
= to
< from;
8157 start
= isBackwards
? to
: from;
8158 end
= isBackwards
? from : to
;
8162 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
8167 * Get an object describing the current selection range in a directional manner
8169 * @return {Object} Object containing 'from' and 'to' offsets
8171 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
8172 var input
= this.$input
[ 0 ],
8173 start
= input
.selectionStart
,
8174 end
= input
.selectionEnd
,
8175 isBackwards
= input
.selectionDirection
=== 'backward';
8178 from: isBackwards
? end
: start
,
8179 to
: isBackwards
? start
: end
8184 * Get the length of the text input value.
8186 * This could differ from the length of #getValue if the
8187 * value gets filtered
8189 * @return {number} Input length
8191 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
8192 return this.$input
[ 0 ].value
.length
;
8196 * Focus the input and select the entire text.
8200 OO
.ui
.TextInputWidget
.prototype.select = function () {
8201 return this.selectRange( 0, this.getInputLength() );
8205 * Focus the input and move the cursor to the start.
8209 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
8210 return this.selectRange( 0 );
8214 * Focus the input and move the cursor to the end.
8218 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
8219 return this.selectRange( this.getInputLength() );
8223 * Insert new content into the input.
8225 * @param {string} content Content to be inserted
8228 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
8230 range
= this.getRange(),
8231 value
= this.getValue();
8233 start
= Math
.min( range
.from, range
.to
);
8234 end
= Math
.max( range
.from, range
.to
);
8236 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
8237 this.selectRange( start
+ content
.length
);
8242 * Insert new content either side of a selection.
8244 * @param {string} pre Content to be inserted before the selection
8245 * @param {string} post Content to be inserted after the selection
8248 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
8250 range
= this.getRange(),
8251 offset
= pre
.length
;
8253 start
= Math
.min( range
.from, range
.to
);
8254 end
= Math
.max( range
.from, range
.to
);
8256 this.selectRange( start
).insertContent( pre
);
8257 this.selectRange( offset
+ end
).insertContent( post
);
8259 this.selectRange( offset
+ start
, offset
+ end
);
8264 * Set the validation pattern.
8266 * The validation pattern is either a regular expression, a function, or the symbolic name of a
8267 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
8268 * value must contain only numbers).
8270 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
8271 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
8273 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
8274 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
8275 this.validate
= validate
;
8277 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
8282 * Sets the 'invalid' flag appropriately.
8284 * @param {boolean} [isValid] Optionally override validation result
8286 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
8288 setFlag = function ( valid
) {
8290 widget
.$input
.attr( 'aria-invalid', 'true' );
8292 widget
.$input
.removeAttr( 'aria-invalid' );
8294 widget
.setFlags( { invalid
: !valid
} );
8297 if ( isValid
!== undefined ) {
8300 this.getValidity().then( function () {
8309 * Check if a value is valid.
8311 * This method returns a promise that resolves with a boolean `true` if the current value is
8312 * considered valid according to the supplied {@link #validate validation pattern}.
8315 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
8317 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
8320 if ( this.validate
instanceof Function
) {
8321 result
= this.validate( this.getValue() );
8322 if ( result
&& $.isFunction( result
.promise
) ) {
8323 return result
.promise();
8325 return $.Deferred().resolve( !!result
).promise();
8328 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
8333 * Get the validity of current value.
8335 * This method returns a promise that resolves if the value is valid and rejects if
8336 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
8338 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
8340 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
8343 function rejectOrResolve( valid
) {
8345 return $.Deferred().resolve().promise();
8347 return $.Deferred().reject().promise();
8351 if ( this.validate
instanceof Function
) {
8352 result
= this.validate( this.getValue() );
8353 if ( result
&& $.isFunction( result
.promise
) ) {
8354 return result
.promise().then( function ( valid
) {
8355 return rejectOrResolve( valid
);
8358 return rejectOrResolve( result
);
8361 return rejectOrResolve( this.getValue().match( this.validate
) );
8366 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
8368 * @param {string} labelPosition Label position, 'before' or 'after'
8371 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
8372 this.labelPosition
= labelPosition
;
8373 this.updatePosition();
8378 * Update the position of the inline label.
8380 * This method is called by #setLabelPosition, and can also be called on its own if
8381 * something causes the label to be mispositioned.
8385 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
8386 var after
= this.labelPosition
=== 'after';
8389 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
8390 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
8392 this.valCache
= null;
8393 this.scrollWidth
= null;
8395 this.positionLabel();
8401 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
8402 * already empty or when it's not editable.
8404 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
8405 if ( this.type
=== 'search' ) {
8406 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
8407 this.setIndicator( null );
8409 this.setIndicator( 'clear' );
8415 * Position the label by setting the correct padding on the input.
8420 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
8421 var after
, rtl
, property
;
8424 // Clear old values if present
8426 'padding-right': '',
8431 this.$element
.append( this.$label
);
8433 this.$label
.detach();
8437 after
= this.labelPosition
=== 'after';
8438 rtl
= this.$element
.css( 'direction' ) === 'rtl';
8439 property
= after
=== rtl
? 'padding-left' : 'padding-right';
8441 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
8449 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8450 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8451 if ( state
.scrollTop
!== undefined ) {
8452 this.$input
.scrollTop( state
.scrollTop
);
8457 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
8458 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
8459 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
8461 * - by typing a value in the text input field. If the value exactly matches the value of a menu
8462 * option, that option will appear to be selected.
8463 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
8466 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8468 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
8471 * // Example: A ComboBoxInputWidget.
8472 * var comboBox = new OO.ui.ComboBoxInputWidget( {
8473 * label: 'ComboBoxInputWidget',
8474 * value: 'Option 1',
8477 * new OO.ui.MenuOptionWidget( {
8479 * label: 'Option One'
8481 * new OO.ui.MenuOptionWidget( {
8483 * label: 'Option Two'
8485 * new OO.ui.MenuOptionWidget( {
8487 * label: 'Option Three'
8489 * new OO.ui.MenuOptionWidget( {
8491 * label: 'Option Four'
8493 * new OO.ui.MenuOptionWidget( {
8495 * label: 'Option Five'
8500 * $( 'body' ).append( comboBox.$element );
8502 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
8505 * @extends OO.ui.TextInputWidget
8508 * @param {Object} [config] Configuration options
8509 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8510 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
8511 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
8512 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
8513 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
8515 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
8516 // Configuration initialization
8517 config
= $.extend( {
8520 // For backwards-compatibility with ComboBoxWidget config
8521 $.extend( config
, config
.input
);
8523 // Parent constructor
8524 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
8527 this.$overlay
= config
.$overlay
|| this.$element
;
8528 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
8532 $container
: this.$element
,
8533 disabled
: this.isDisabled()
8537 // For backwards-compatibility with ComboBoxWidget
8541 this.$indicator
.on( {
8542 click
: this.onIndicatorClick
.bind( this ),
8543 keypress
: this.onIndicatorKeyPress
.bind( this )
8545 this.connect( this, {
8546 change
: 'onInputChange',
8547 enter
: 'onInputEnter'
8549 this.menu
.connect( this, {
8550 choose
: 'onMenuChoose',
8551 add
: 'onMenuItemsChange',
8552 remove
: 'onMenuItemsChange'
8558 'aria-autocomplete': 'list'
8560 // Do not override options set via config.menu.items
8561 if ( config
.options
!== undefined ) {
8562 this.setOptions( config
.options
);
8564 // Extra class for backwards-compatibility with ComboBoxWidget
8565 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
8566 this.$overlay
.append( this.menu
.$element
);
8567 this.onMenuItemsChange();
8572 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
8577 * Get the combobox's menu.
8578 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
8580 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
8585 * Get the combobox's text input widget.
8586 * @return {OO.ui.TextInputWidget} Text input widget
8588 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
8593 * Handle input change events.
8596 * @param {string} value New value
8598 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
8599 var match
= this.menu
.getItemFromData( value
);
8601 this.menu
.selectItem( match
);
8602 if ( this.menu
.getHighlightedItem() ) {
8603 this.menu
.highlightItem( match
);
8606 if ( !this.isDisabled() ) {
8607 this.menu
.toggle( true );
8612 * Handle mouse click events.
8615 * @param {jQuery.Event} e Mouse click event
8617 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
8618 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8620 this.$input
[ 0 ].focus();
8626 * Handle key press events.
8629 * @param {jQuery.Event} e Key press event
8631 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
8632 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
8634 this.$input
[ 0 ].focus();
8640 * Handle input enter events.
8644 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
8645 if ( !this.isDisabled() ) {
8646 this.menu
.toggle( false );
8651 * Handle menu choose events.
8654 * @param {OO.ui.OptionWidget} item Chosen item
8656 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
8657 this.setValue( item
.getData() );
8661 * Handle menu item change events.
8665 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
8666 var match
= this.menu
.getItemFromData( this.getValue() );
8667 this.menu
.selectItem( match
);
8668 if ( this.menu
.getHighlightedItem() ) {
8669 this.menu
.highlightItem( match
);
8671 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
8677 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
8679 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8682 this.menu
.setDisabled( this.isDisabled() );
8689 * Set the options available for this input.
8691 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8694 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
8697 .addItems( options
.map( function ( opt
) {
8698 return new OO
.ui
.MenuOptionWidget( {
8700 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
8709 * @deprecated Use OO.ui.ComboBoxInputWidget instead.
8711 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
8714 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8715 * which is a widget that is specified by reference before any optional configuration settings.
8717 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8719 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8720 * A left-alignment is used for forms with many fields.
8721 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8722 * A right-alignment is used for long but familiar forms which users tab through,
8723 * verifying the current field with a quick glance at the label.
8724 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8725 * that users fill out from top to bottom.
8726 * - **inline**: The label is placed after the field-widget and aligned to the left.
8727 * An inline-alignment is best used with checkboxes or radio buttons.
8729 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8730 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8734 * @extends OO.ui.Layout
8735 * @mixins OO.ui.mixin.LabelElement
8736 * @mixins OO.ui.mixin.TitledElement
8739 * @param {OO.ui.Widget} fieldWidget Field widget
8740 * @param {Object} [config] Configuration options
8741 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8742 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8743 * The array may contain strings or OO.ui.HtmlSnippet instances.
8744 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8745 * The array may contain strings or OO.ui.HtmlSnippet instances.
8746 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8747 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8748 * For important messages, you are advised to use `notices`, as they are always shown.
8750 * @throws {Error} An error is thrown if no widget is specified
8752 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8753 var hasInputWidget
, div
;
8755 // Allow passing positional parameters inside the config object
8756 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8757 config
= fieldWidget
;
8758 fieldWidget
= config
.fieldWidget
;
8761 // Make sure we have required constructor arguments
8762 if ( fieldWidget
=== undefined ) {
8763 throw new Error( 'Widget not found' );
8766 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8768 // Configuration initialization
8769 config
= $.extend( { align
: 'left' }, config
);
8771 // Parent constructor
8772 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8774 // Mixin constructors
8775 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8776 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8779 this.fieldWidget
= fieldWidget
;
8782 this.$field
= $( '<div>' );
8783 this.$messages
= $( '<ul>' );
8784 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8786 if ( config
.help
) {
8787 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8788 classes
: [ 'oo-ui-fieldLayout-help' ],
8794 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8795 div
.html( config
.help
.toString() );
8797 div
.text( config
.help
);
8799 this.popupButtonWidget
.getPopup().$body
.append(
8800 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8802 this.$help
= this.popupButtonWidget
.$element
;
8804 this.$help
= $( [] );
8808 if ( hasInputWidget
) {
8809 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8811 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8815 .addClass( 'oo-ui-fieldLayout' )
8816 .append( this.$help
, this.$body
);
8817 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8818 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8820 .addClass( 'oo-ui-fieldLayout-field' )
8821 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8822 .append( this.fieldWidget
.$element
);
8824 this.setErrors( config
.errors
|| [] );
8825 this.setNotices( config
.notices
|| [] );
8826 this.setAlignment( config
.align
);
8831 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8832 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8833 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8838 * Handle field disable events.
8841 * @param {boolean} value Field is disabled
8843 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8844 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8848 * Handle label mouse click events.
8851 * @param {jQuery.Event} e Mouse click event
8853 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8854 this.fieldWidget
.simulateLabelClick();
8859 * Get the widget contained by the field.
8861 * @return {OO.ui.Widget} Field widget
8863 OO
.ui
.FieldLayout
.prototype.getField = function () {
8864 return this.fieldWidget
;
8869 * @param {string} kind 'error' or 'notice'
8870 * @param {string|OO.ui.HtmlSnippet} text
8873 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8874 var $listItem
, $icon
, message
;
8875 $listItem
= $( '<li>' );
8876 if ( kind
=== 'error' ) {
8877 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8878 } else if ( kind
=== 'notice' ) {
8879 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8883 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8885 .append( $icon
, message
.$element
)
8886 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8891 * Set the field alignment mode.
8894 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8897 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8898 if ( value
!== this.align
) {
8899 // Default to 'left'
8900 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8904 if ( value
=== 'inline' ) {
8905 this.$body
.append( this.$field
, this.$label
);
8907 this.$body
.append( this.$label
, this.$field
);
8909 // Set classes. The following classes can be used here:
8910 // * oo-ui-fieldLayout-align-left
8911 // * oo-ui-fieldLayout-align-right
8912 // * oo-ui-fieldLayout-align-top
8913 // * oo-ui-fieldLayout-align-inline
8915 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8917 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8925 * Set the list of error messages.
8927 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
8928 * The array may contain strings or OO.ui.HtmlSnippet instances.
8931 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
8932 this.errors
= errors
.slice();
8933 this.updateMessages();
8938 * Set the list of notice messages.
8940 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
8941 * The array may contain strings or OO.ui.HtmlSnippet instances.
8944 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
8945 this.notices
= notices
.slice();
8946 this.updateMessages();
8951 * Update the rendering of error and notice messages.
8955 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
8957 this.$messages
.empty();
8959 if ( this.errors
.length
|| this.notices
.length
) {
8960 this.$body
.after( this.$messages
);
8962 this.$messages
.remove();
8966 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
8967 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
8969 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
8970 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
8975 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8976 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8977 * is required and is specified before any optional configuration settings.
8979 * Labels can be aligned in one of four ways:
8981 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8982 * A left-alignment is used for forms with many fields.
8983 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8984 * A right-alignment is used for long but familiar forms which users tab through,
8985 * verifying the current field with a quick glance at the label.
8986 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8987 * that users fill out from top to bottom.
8988 * - **inline**: The label is placed after the field-widget and aligned to the left.
8989 * An inline-alignment is best used with checkboxes or radio buttons.
8991 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8992 * text is specified.
8995 * // Example of an ActionFieldLayout
8996 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8997 * new OO.ui.TextInputWidget( {
8998 * placeholder: 'Field widget'
9000 * new OO.ui.ButtonWidget( {
9004 * label: 'An ActionFieldLayout. This label is aligned top',
9006 * help: 'This is help text'
9010 * $( 'body' ).append( actionFieldLayout.$element );
9013 * @extends OO.ui.FieldLayout
9016 * @param {OO.ui.Widget} fieldWidget Field widget
9017 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9019 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9020 // Allow passing positional parameters inside the config object
9021 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9022 config
= fieldWidget
;
9023 fieldWidget
= config
.fieldWidget
;
9024 buttonWidget
= config
.buttonWidget
;
9027 // Parent constructor
9028 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9031 this.buttonWidget
= buttonWidget
;
9032 this.$button
= $( '<div>' );
9033 this.$input
= $( '<div>' );
9037 .addClass( 'oo-ui-actionFieldLayout' );
9039 .addClass( 'oo-ui-actionFieldLayout-button' )
9040 .append( this.buttonWidget
.$element
);
9042 .addClass( 'oo-ui-actionFieldLayout-input' )
9043 .append( this.fieldWidget
.$element
);
9045 .append( this.$input
, this.$button
);
9050 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9053 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9054 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9055 * configured with a label as well. For more information and examples,
9056 * please see the [OOjs UI documentation on MediaWiki][1].
9059 * // Example of a fieldset layout
9060 * var input1 = new OO.ui.TextInputWidget( {
9061 * placeholder: 'A text input field'
9064 * var input2 = new OO.ui.TextInputWidget( {
9065 * placeholder: 'A text input field'
9068 * var fieldset = new OO.ui.FieldsetLayout( {
9069 * label: 'Example of a fieldset layout'
9072 * fieldset.addItems( [
9073 * new OO.ui.FieldLayout( input1, {
9074 * label: 'Field One'
9076 * new OO.ui.FieldLayout( input2, {
9077 * label: 'Field Two'
9080 * $( 'body' ).append( fieldset.$element );
9082 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9085 * @extends OO.ui.Layout
9086 * @mixins OO.ui.mixin.IconElement
9087 * @mixins OO.ui.mixin.LabelElement
9088 * @mixins OO.ui.mixin.GroupElement
9091 * @param {Object} [config] Configuration options
9092 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9094 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9095 // Configuration initialization
9096 config
= config
|| {};
9098 // Parent constructor
9099 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9101 // Mixin constructors
9102 OO
.ui
.mixin
.IconElement
.call( this, config
);
9103 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9104 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9106 if ( config
.help
) {
9107 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9108 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9113 this.popupButtonWidget
.getPopup().$body
.append(
9115 .text( config
.help
)
9116 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9118 this.$help
= this.popupButtonWidget
.$element
;
9120 this.$help
= $( [] );
9125 .addClass( 'oo-ui-fieldsetLayout' )
9126 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9127 if ( Array
.isArray( config
.items
) ) {
9128 this.addItems( config
.items
);
9134 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9135 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9136 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9137 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9140 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9141 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9142 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9143 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9145 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9146 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9147 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9148 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9149 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9150 * often have simplified APIs to match the capabilities of HTML forms.
9151 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9153 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9154 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9157 * // Example of a form layout that wraps a fieldset layout
9158 * var input1 = new OO.ui.TextInputWidget( {
9159 * placeholder: 'Username'
9161 * var input2 = new OO.ui.TextInputWidget( {
9162 * placeholder: 'Password',
9165 * var submit = new OO.ui.ButtonInputWidget( {
9169 * var fieldset = new OO.ui.FieldsetLayout( {
9170 * label: 'A form layout'
9172 * fieldset.addItems( [
9173 * new OO.ui.FieldLayout( input1, {
9174 * label: 'Username',
9177 * new OO.ui.FieldLayout( input2, {
9178 * label: 'Password',
9181 * new OO.ui.FieldLayout( submit )
9183 * var form = new OO.ui.FormLayout( {
9184 * items: [ fieldset ],
9185 * action: '/api/formhandler',
9188 * $( 'body' ).append( form.$element );
9191 * @extends OO.ui.Layout
9192 * @mixins OO.ui.mixin.GroupElement
9195 * @param {Object} [config] Configuration options
9196 * @cfg {string} [method] HTML form `method` attribute
9197 * @cfg {string} [action] HTML form `action` attribute
9198 * @cfg {string} [enctype] HTML form `enctype` attribute
9199 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9201 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9204 // Configuration initialization
9205 config
= config
|| {};
9207 // Parent constructor
9208 OO
.ui
.FormLayout
.parent
.call( this, config
);
9210 // Mixin constructors
9211 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9214 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9216 // Make sure the action is safe
9217 action
= config
.action
;
9218 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
9219 action
= './' + action
;
9224 .addClass( 'oo-ui-formLayout' )
9226 method
: config
.method
,
9228 enctype
: config
.enctype
9230 if ( Array
.isArray( config
.items
) ) {
9231 this.addItems( config
.items
);
9237 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9238 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9243 * A 'submit' event is emitted when the form is submitted.
9248 /* Static Properties */
9250 OO
.ui
.FormLayout
.static.tagName
= 'form';
9255 * Handle form submit events.
9258 * @param {jQuery.Event} e Submit event
9261 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9262 if ( this.emit( 'submit' ) ) {
9268 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9269 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9272 * // Example of a panel layout
9273 * var panel = new OO.ui.PanelLayout( {
9277 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9279 * $( 'body' ).append( panel.$element );
9282 * @extends OO.ui.Layout
9285 * @param {Object} [config] Configuration options
9286 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9287 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9288 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9289 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9291 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
9292 // Configuration initialization
9293 config
= $.extend( {
9300 // Parent constructor
9301 OO
.ui
.PanelLayout
.parent
.call( this, config
);
9304 this.$element
.addClass( 'oo-ui-panelLayout' );
9305 if ( config
.scrollable
) {
9306 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
9308 if ( config
.padded
) {
9309 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9311 if ( config
.expanded
) {
9312 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9314 if ( config
.framed
) {
9315 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9321 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9326 * Focus the panel layout
9328 * The default implementation just focuses the first focusable element in the panel
9330 OO
.ui
.PanelLayout
.prototype.focus = function () {
9331 OO
.ui
.findFocusable( this.$element
).focus();
9335 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
9336 * items), with small margins between them. Convenient when you need to put a number of block-level
9337 * widgets on a single line next to each other.
9339 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
9342 * // HorizontalLayout with a text input and a label
9343 * var layout = new OO.ui.HorizontalLayout( {
9345 * new OO.ui.LabelWidget( { label: 'Label' } ),
9346 * new OO.ui.TextInputWidget( { value: 'Text' } )
9349 * $( 'body' ).append( layout.$element );
9352 * @extends OO.ui.Layout
9353 * @mixins OO.ui.mixin.GroupElement
9356 * @param {Object} [config] Configuration options
9357 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
9359 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
9360 // Configuration initialization
9361 config
= config
|| {};
9363 // Parent constructor
9364 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
9366 // Mixin constructors
9367 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9370 this.$element
.addClass( 'oo-ui-horizontalLayout' );
9371 if ( Array
.isArray( config
.items
) ) {
9372 this.addItems( config
.items
);
9378 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
9379 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);